[英]Replace regular expression javascript
我有這樣的字符串
|1.774|1.78|1|||||1.781|1||||||||
我應用了替換表達式
str = str.replace(/\|\|/g, '| |')
輸出結果是
|1.774|1.78|1| || ||1.781|1| || || || |
但結果一定是這樣的
|1.774|1.78|1| | | | |1.781|1| | | | | | | |
錯誤在哪里? 謝謝
你需要在這里使用前瞻來檢查一個|
之后|
:
str = str.replace(/\|(?=\|)/g, '| ')
請參閱正則表達式演示
細節
\\|
- 文字|
(?=\\|)
- 匹配但不消耗下一個|
的正向前瞻 char,因此將其保持在匹配之外,並且在下一次迭代期間仍可以匹配此char。 只是為了好玩,而不是使用正則表達式,您可以使用以下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的正則表達式很漂亮,但我只是覺得我會提供一個簡單的JS版本。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.