Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript regex to replace numbers in sequence

I am trying to replace numbers in string with the character "X" which works pretty good by replacing every individual number.

This the code:

 let htmlStr = initialString.replace(/[0-9]/g, "X");

So in a case scenario that initialString = "p3d8" the output would be "pXdX"

The aim is to replace a sequence of numbers with a single "X" and not every number (in the sequence) individually. For example:

If initialString = "p348" , with the above code, the output would be "pXXX". How can I make it "pX" - set an "X" for the whole numbers sequence.

Is that doable through regex?

Any help would be welcome

like image 816
George George Avatar asked Jan 28 '26 15:01

George George


2 Answers

Try

let htmlStr = "p348".replace(/[0-9]+/g, "X");
let htmlStr2 = "p348ad3344ddds".replace(/[0-9]+/g, "X");

let htmlStr3 = "p348abc64d".replace(/\d+/g, "X");

console.log("p348           =>",htmlStr);
console.log("p348ad3344ddds =>", htmlStr2);
console.log("p348abc64d     =>", htmlStr3);

In regexp the \d is equivalent to [0-9], the plus + means that we match at least one digit (so we match whole consecutive digits sequence). More info here or regexp mechanism movie here.

like image 112
Kamil Kiełczewski Avatar answered Jan 30 '26 05:01

Kamil Kiełczewski


You can use + after [0-9] It will match any number(not 0) of number. Check Quantifiers. for more info

let initialString = "p345";
let htmlStr = initialString.replace(/[0-9]+/g, "X");
console.log(htmlStr);
like image 22
Maheer Ali Avatar answered Jan 30 '26 05:01

Maheer Ali



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!