I have a few strings like so:
str1 = "00001011100000"; // 10111
str2 = "00011101000000"; // 11101
...
I would like to strip the leading AND closing zeros from every string using regex with ONE operation.
So far I used two different functions but I would like to combine them together:
str.replace(/^0+/,'').replace(/0+$/,'');
You can just combine both of your regex using an OR
clause (|
):
var r = '00001011100000'.replace(/^0+|0+$/g, "");
//=> "10111"
update: Above regex solutions replaces 0
with an empty string. To prevent this problem use this regex:
var repl = str.replace(/^0+(\d)|(\d)0+$/gm, '$1$2');
RegEx Breakup:
^
: Assert start0+
: Match one or more zeroes(\d)
: Followed by a digit that is captured in capture group #1|
: OR(\d)
: Match a digit that is captured in capture group #20+
: Followed by one or more zeroes$
: Assert endReplacement:
Here we are using two back-references of the tow capturing groups:
$1$2
That basically puts digit after leading zeroes and digit before trailing zeroes back in the replacement.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments