0

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?

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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)

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.