localZero localZero - 14 days ago 5
Javascript Question

Replace a number in a string

Ok so i have the following string,

var str = 'some text {Foo} some more text {9}';


Now i know how to replace specific characters/words like,

var newStr = str.replace(/{Foo}/g, 'bar');


But how would i replace that {9} when the number can be any number?

Answer

You could use the meta sequence for a digit \d.

var str = 'some text {Foo} some more text {9}',
    newStr = str.replace(/{\d+}/g, 'bar');

console.log(newStr);