1

I want to add a * before every number in a string.

/-200,/-    -->   /-*200,/-

I tried using .replace(/0/g,'*0'), .replace(/1/g,'*1') ... but that did not work for multiple digit numbers.

1 Answer 1

3
.replace(/(\d+)/g, "*$1")

That is, match each instance of one or more digits with \d+ - where \d matches any digit and + means one or more. And use parentheses to make it a capturing group so that you can refer to the match in the replacement string as $1.

console.log("/-200,/-".replace(/(\d+)/g, "*$1"))
console.log("100, 200, 300".replace(/(\d+)/g, "*$1"))
console.log("A number: 123; a second number: 321".replace(/(\d+)/g, "*$1"))

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

Comments

Your Answer

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