I am stuck with a little regular expression
I am trying to match every substring that start with a given prefix using regular expression
in javascript
prefix = "pre-"
regex = /???/
"pre-foo-bar bar pre-bar barfoo".replace(regex, '')
// should output "bar barfoo"
/\bpre-\S*\s?/gworks, assuming you want to strip out the trailing space as well (per your example). If you want to leave it in, use/\bpre-\S*/gCorrection
\bonly looks up word characters, and-is definitely not a word character. Unfortunately, JavaScript doesn’t support custom lookbehinds./(\s|^)pre-\S*/gshould work, but there will be a leading space compared to the example output given above. This checks for “pre-” preceded either by nothing or a space character and then followed by 0 or more non-space characters. It removes the whole block except the space. If the space is really important to you, you could do:Second Correction
The complex replace I gave you won’t work if you have two in a row like, “pre-a pre-b pre-c”. You’ll end up with
"pre-b "because of the\s?at the end. Your best bet to get the exact desired output is to use/(\s|^)pre-\S*/gand check the original string if it started with “pre-” if so, just remove one space from the beginning.