1

I am Trying to get my head around some regex using JS .replace to replace an integer with a string.

For example, the string could be:

 var string = 'item_descriptions_0_additional_details';

I want to replace the 0 with another value. I was originally using this:

string.replace( /\[\d\]/g, '[newvalue]');

But it is not working. I am very new in Regex.

Thanks in advance. Greatly appreciated.

0

3 Answers 3

1

What you have

\[\d\]
  • \[ - Means match [
  • \d - Match any digit
  • \] - Match ]

since in your string you don't have any sequence which matches the regex pattern so it is not doing any replace


You need to use \d

var string = 'item_descriptions_0_additional_details';

let op = string.replace( /\d/g, '[new value]');

console.log(op)

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

Comments

1

First, because string.replace returns a new string, it doesn't mutate the old string, so you need to assign the result of string.replace to a variable. Second, you have an invalid regex:

var string = 'item_descriptions_0_additional_details';

string = string.replace( /\d+/g, '[newvalue]');

console.log(string);

Comments

1

Try \d+ for capture first occurrence of any sequence of digits (with length at least one char)

var string = 'item_descriptions_0_additional_details';

var r = string.replace(/\d+/,'[new value]');

console.log(r);

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.