0

I want to replace few characters if we already know the prefix of those character. Ex: If my string is

limit=100&launch_year=2016&

and i want to replace it with

limit=100&launch_year=2017&

But the string is dynamic and we only know launch_year, so is it possible to find 2016 and replace it with 2017 if i only know that there is launch_year in the dynamic string.

2 Answers2

0

String replace with regex /(.*limit=100&launch_year=)\d{4}(.*)/.

Capture the prefix and suffix around the year value you want to replace and rebuild the string with new year.

const data = "limit=100&launch_year=2016&";

const regex = /(.*launch_year=)\d{4}(.*)/;

const replaceYear = (data, year) => data.replace(regex, `$1${year}$2`);

console.log(replaceYear(data, "2017"));
console.log(replaceYear(data, "2020"));
Drew Reese
  • 165,259
  • 14
  • 153
  • 181
  • 1
    Hi @drew-reese, may I suggest to keep the regex even more generic, as the `data` string seems to be a query string and its content might vary? I think `/(.*launch_year=)\d{4}(.*)/` would be a better fit, in this case. – secan Oct 06 '20 at 08:11
0

It seems like your input is a query string so I would suggest to use parser and then change it...

const queryParams = new URLSearchParams('limit=100&launch_year=2016');
queryParams.set('launch_year','2017');
console.log(queryParams.toString() + '&' ); 
// "limit=100&launch_year=2017&"
adir abargil
  • 5,495
  • 3
  • 19
  • 29