4

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

0

2 Answers 2

6

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.
Sign up to request clarification or add additional context in comments.

1 Comment

That response in 40 seconds tho ^^
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.