本文介绍了从字符串中删除前导零和尾随零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有几个这样的字符串:
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+$/,'');
推荐答案
您可以使用 OR 子句( |
):
var r = '00001011100000'.replace(/^0+|0+$/g, "");
//=> "10111"
更新:以上正则表达式解决方案用空字符串替换 0
。要防止出现此问题,请使用此正则表达式:
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分手:
-
^
:断言开始 -
0 +
:匹配一个或多个零 -
(\d)
:后跟在捕获组#1中捕获的数字 -
|
:OR -
(\d)
:匹配捕获组#2中捕获的数字 -
0 +
:后跟一个或多个零 -
$
:断言结束
^
: 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 end
替换:
这里我们使用两个捕获组的反向引用:
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.
这篇关于从字符串中删除前导零和尾随零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!