Home > OS >  JS string.replace() is url encoding string
JS string.replace() is url encoding string

Time:11-21

I'm trying to replace a tag element in a URL using the code below. The actual replace works well but for some reason it's also changing the code to be URL encoded, for example & becomes & - why is this?

let url = 'https://www.amazon.co.uk/Apple-iPhone-14-Pro-128/dp/B0BDJC5HW8?_encoding=UTF8&pd_rd_w=2pD6L&tag=gg99-33&blah=blah'

url = url.replace(/&tag=[\w-] &/, '&tag=abc-123')

console.log(url)

Becomes:

https://www.amazon.co.uk/Apple-iPhone-14-Pro-128/dp/B0BDJC5HW8?_encoding=UTF8&pd_rd_w=2pD6L&tag=abc-123&blah=blah

It should become:

https://www.amazon.co.uk/Apple-iPhone-14-Pro-128/dp/B0BDJC5HW8?_encoding=UTF8&pd_rd_w=2pD6L&tag=abc-123&blah=blah

CodePudding user response:

If this string is a valid URL, you can construct a URL object and change its search parameters, here is an example:

const url = 'https://www.amazon.co.uk/Apple-iPhone-14-Pro-128/dp/B0BDJC5HW8?_encoding=UTF8&pd_rd_w=2pD6L&tag=gg99-33'
const urlObj = new URL(url);
urlObj.searchParams.set('tag', 'abc-123');
const newURL = urlObj.toString();

console.log(newURL);

  • Related