Pierre
Pierre

Reputation: 686

Match substring that start with prefix

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"

Upvotes: 3

Views: 4821

Answers (3)

Aurimas Ličkus
Aurimas Ličkus

Reputation: 10074

Use this

var string = 'pre-foo-bar bar pre-bar barfoo';  
string.replace(/pre-[\w\S]+/ig,'');

Upvotes: 1

xanatos
xanatos

Reputation: 111820

var str =  'pre-foo-bar   f-pre-foo-bar  bar pre-pre pre-bar barfoopre- pre-a pre-b pre-c';  

str = str.replace(/(^|\s+)pre-\S*(?=\s+|$)/g, '$1');

document.write('<pre>' + str + '</pre>');

http://jsfiddle.net/qTADZ/5/

We look for strings that start with a space or at the beginning of the string (^|\s), that must begin with pre- and we take all the non space characters followed by one or more spaces or the end of the string \S*(?=\s+|$). We remove everything but the initial space/beginning of the string $1 (that references (^|\s) )

Upvotes: 1

Brian Nickel
Brian Nickel

Reputation: 27550

/\bpre-\S*\s?/g works, assuming you want to strip out the trailing space as well (per your example). If you want to leave it in, use /\bpre-\S*/g

Correction

\b only looks up word characters, and - is definitely not a word character. Unfortunately, JavaScript doesn't support custom lookbehinds.

/(\s|^)pre-\S*/g should 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:

str.replace(/(\s|^)pre-\S*\s?/g, function(wholeString, optionalSpaceCharacter) {
    return optionalSpaceCharacter;
});

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*/g and check the original string if it started with "pre-" if so, just remove one space from the beginning.

str.replace(/(\s|^)pre-\S*/g, '').substring(str.substring(0, 4) == "pre-" ? 1 : 0);

Upvotes: 3

Related Questions