[英]Replace regular expression javascript
I have a string like this 我有这样的字符串
|1.774|1.78|1|||||1.781|1||||||||
I applied a replace expression 我应用了替换表达式
str = str.replace(/\|\|/g, '| |')
Output result is 输出结果是
|1.774|1.78|1| || ||1.781|1| || || || |
but the result must be like 但结果一定是这样的
|1.774|1.78|1| | | | |1.781|1| | | | | | | |
Where is the error? 错误在哪里? Thanks 谢谢
You need to use a lookahead here to check for a |
你需要在这里使用前瞻来检查一个|
after a |
之后|
: :
str = str.replace(/\|(?=\|)/g, '| ')
See the regex demo 请参阅正则表达式演示
Details 细节
\\|
- a literal |
- 文字|
(?=\\|)
- a positive lookahead that matches but does not consume the next |
(?=\\|)
- 匹配但不消耗下一个|
的正向前瞻 char, thus keeping it outside of the match and this char is still available to be matched during the next iteration. char,因此将其保持在匹配之外,并且在下一次迭代期间仍可以匹配此char。 Just for fun, instead of using a regular expression you can use the following javascript function: 只是为了好玩,而不是使用正则表达式,您可以使用以下javascript函数:
let original = '|1.774|1.78|1|||||1.781|1||||||||';
let str = original.split('|').map((e, i, arr) => {
// 1) if the element is not on the end of the split array...
// 2) and if element is empty ('')
// -> there's no data between '|' chars, so convert from empty string to space (' ')
if (i > 0 && i < arr.length -1 && e === '') return ' ';
// otherwise return original '|' if there is data found OR if element is on the end
// -> of the split array
else return e
}).join('|')
Wiktor's regex is quite beautiful, but I just thought I'd offer a plain JS version. Wiktor的正则表达式很漂亮,但我只是觉得我会提供一个简单的JS版本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.