Panagiotis Panagiotis - 2 months ago 9
Javascript Question

JavaScript: Extract part of string between two optional characters with Regex

I'm working on a regex in javascript for capturing part of the string between two optional characters.

Optional characters are: '=' and '||'

Scenarios:


  • LENGTH=A simple message||5

  • LENGTH=A simple message

  • LENGTH||5



For getting the value after '||' I manage that with the split() function.

For getting the 'A simple message' part I manage to extract the string with the regex
match(/\=(.*)\|\|/).pop()
when both '=' and '||' are in the string.

Any suggestions for extracting the string with one regex when one of the two optional characters is there?

I tried also
/(\=)?(.*)(\|\|)?/
but is not working.

Answer

You can use this negative lookahead based regex to capture value from = and optional ||:

/=((?:(?!\|\|).)*)/

RegEx Demo

Comments