Mitchell Simoens
Mitchell Simoens

Reputation: 2536

JavaScript/RegExp replace portion of string

I have a string something like:

foo title:2012-01-01 bar

Where I need to get the 'title:2012-01-01' and replace the date part '2012-01-01' to a special format. I just am not good at RegExp and currently have:

'foo from:2012-01-01 bar'.replace(/from:([a-z0-9-]+)/i, function() {
    console.log(arguments);
    return 'replaced';
})

and that returns

foo replaced bar 

which is a start but not exactly correct. I need the 'from:' not to be replaced, just the '2012-01-01' be replaced. Tried using (?:from:) but that didn't stop it from replacing 'from:'. Also, I need to take into account that there may be a space between 'from:' and '2012-01-01' so it needs to match this also:

foo title: 2012-01-01 bar

Upvotes: 1

Views: 346

Answers (2)

Godwin
Godwin

Reputation: 9907

If the format is always from:... there should be no need to capture the 'from' text at all:

'foo from:2012-01-01 bar'.replace(/from:\s*([a-z0-9-]+)/i, function() {
    console.log(arguments);
    return 'from: replaced';
});

If you want to retain the spacing however, you could do the following:

'foo from:2012-01-01 bar'.replace(/from:(\s*)([a-z0-9-]+)/i, function(match, $1) {
    console.log(arguments);
    return 'from:' + $1 + 'replaced';
});

Upvotes: 0

Daedalus
Daedalus

Reputation: 7722

The following should do what you need it to; tested it myself:

'foo from:2012-01-01 bar'.replace(/(\w+:\s?)([a-z0-9-]+)/i, function(match, $1) {
    console.log(arguments);
    return $1 + 'replaced';
});

DEMO

It will match both title: etc and from:etc. The $1 is the first matched group, the (\w+:\s?), the \w matches any word character, while the \s? matches for at least one or no spaces.

Upvotes: 3

Related Questions