gsamaras gsamaras - 2 months ago 17
HTML Question

Replace value of id in URL

I have URLs of that form:


https://www.merkel.com/obama?trump=15&id=9616071454&hilarry=es


I would like, via to replace 9616071454 with 1, for example.

I know about the replace(), but this will replace "id" itself, not the value of "id".

Is there anything common in the web dev world? :)

Answer

The solution considering situations when:

  • id param can contain other characters besides digits
  • avoiding fragment # replacement when id is followed by #

var str = 'https://www.foo.com/bar?trump=15&hilarry=es&id=961607some1454text#fragment',
    newId = 1,
    replaced = str.replace(/\bid=[^&#]+/g, "id=" + newId);

console.log(replaced); // "https://www.foo.com/bar?trump=15&hilarry=es&id=1#fragment"
Comments