1

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
3
  • Somewhat confused: is 'title' a keyword? What about 'from'? Or are you looking for any word followed by a colon? Giving us at least one example of both expected inputs and outputs would be tremendously helpful here. Commented Jul 31, 2012 at 20:28
  • Also, is logging the arguments a requirement or is this just debug code? Commented Jul 31, 2012 at 20:31
  • 'title' was a typo on my part, should have been 'from'. The console.log(arguments) is just debug code, will be doing some date calc later. Commented Jul 31, 2012 at 21:29

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

If you're looking for at least one space (possibly more) I would suggest replacing the \s? with \s* (zero or more space characters).
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.