Reputation: 457
I have the below Path/URL
test = "/test/test-products/?pId=9401100&imgId=14607518&catID=5449&modelId=pros&cm_sp=XIT_resp-_-PR-_-14607518_9401100&lid=xit-test-14607518-9401100";
newPath = test.replace('14607518', '12345678');
Not updating every occurrences of the matching string though it has hypen,underscore(-_-)
How can I replace all occurrences of 14607518 with regex
?
Upvotes: 0
Views: 59
Reputation: 20737
You should use:
([^\d])(14607518)([^\d])
because it will help you to avoid accidentally targeting numbers such as 146075189
const regex = /([^\d])(14607518)([^\d])/gm;
const str = `/test/test-products/?pId=9401100&imgId=146075189&catID=5449&modelId=pros&cm_sp=XIT_resp-_-PR-_-14607518_9401100&lid=xit-test-14607518-9401100`;
const subst = `$112345678$3`;
// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);
See https://regex101.com/r/0pJWwo/1
Upvotes: 0
Reputation: 37755
When you pass a string instead of regex object to replace it just replaces the first occurrence only, You need to use a g
tag and regex pattern to replace all the instances
const test = "/test/test-products/?pId=9401100&imgId=14607518&catID=5449&modelId=pros&cm_sp=XIT_resp-_-PR-_-14607518_9401100&lid=xit-test-14607518-9401100";
const newPath = test.replace(/14607518/g, '12345678');
console.log(newPath)
Upvotes: 1
Reputation: 591
The syntax is a bit different since you're using regex here.
test.replace(/14607518/g, '12345678');
Instead of
test.replace('14607518', '12345678');
Where the 'g' at the end means 'global', or replace all occurrences.
Upvotes: 1