Front-end URL splicing path parameters

1. Application scenarios

We sometimes encounter scenarios where browser URL splicing parameters are used. For example, when the page jumps, a specific logo is attached: https://www.baidu.com?from=csdn

2. Specific implementation

1. String concatenation

The first thing we can think of is to use string concatenation to achieve

const baseUrl = 'https://www.baidu.com'
const url = baseUrl  + '?from=csdn'

But if the URL to be jumped is not fixed, for example:

const baseUrl = 'https://www.baidu.com/s?wd=time'
const url = baseUrl  + '&from=csdn'

So when splicing parameters, we must first determine whether the original url already contains parameters. If not, it should start with ?, otherwise it should start with &beginning

2.URL object implementation

We can use the URL API provided by the browser (not compatible with IE)

  const url = new URL("https://www.baidu.com/s?wd=time");
  console.log(url)

Insert image description here
We will get a parsed URL object
If we want to add parameters, directly searchParamsJust add it to the object

  const url = new URL("https://www.baidu.com/s?wd=time");
  url.searchParams.append('from', 'csdn');
  console.log(url)

Insert image description here
In this way, our parameters have been added. We only need to call the url.toString() method to get the complete path

4. Complete code

  const url = new URL("https://www.baidu.com/s?wd=time");
  url.searchParams.append('from', 'csdn');
  console.log(url)
  console.log(url.toString())

Insert image description here

Guess you like

Origin blog.csdn.net/weixin_43845090/article/details/133792599