简体   繁体   中英

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

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.

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';
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM