Search code examples
javascriptregexstringstring-matching

Match everything outside of two strings


For an input of

*something here*another stuff here

I want to match everything that's outside of the two asterisk (*).

Expected output after regex:

another stuff here

I figured out how to match everything inside of the (*) /(?<=\*)(.*)(?=\*)/ but I can't match everything outside. Noticed that I don't wish to match the *.


Solution

  • You can remove substring(s) between asterisks and trim the string after:

    s.replace(/\*[^*]*\*/g, '').trim()
    s.replace(/\*.*?\*/g, '').trim()
    

    See the regex demo.

    Details

    • \* - an asterisk
    • [^*]* - any zero or more chars other than an asterisk
    • .*? - any zero or more chars other than line break chars, as few as possible (NOTE: if you use .*, you will get an unexpected output in case when the string has multiple substrings between asterisks)
    • \* - an asterisk

    See a JavaScript demo:

    console.log("*something here*another stuff here".replace(/\*[^*]*\*/g, '').trim())
    // => another stuff here