简体   繁体   中英

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.

Just for fun, instead of using a regular expression you can use the following javascript function:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM