user2400026
user2400026

Reputation:

Javascript extract regular expression from string

I've tried a few ways of doing this and I can't figure out why my .match always returns null. Given the string below how can I extract the 04-Jun-2017 into it's own variable?

var str = "I need the only the    date 04-Jun-2017\n"

str.replace(/\n/g,' ');
var date = str.match(/^[01][0-9]-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-\d{4}$/);
alert(date)

Upvotes: 1

Views: 3984

Answers (2)

Jesus Walker
Jesus Walker

Reputation: 144

At first you should be more clear about your question. Second here's what may be the answer

var str = "I need the only the    date 04-Jun-2017\n"
var result  = str.replace('I need the only the    ','');
alert(result);

See how the .replace(valueToSearch,valueToReplace) function needs two parameters, first is the text to replace, so what ever you put inside it will search for inside the string, the second parameter is the value that it will replace it with, so in case you want to get rid of it just place an empty string.

Upvotes: -1

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626689

First of all, str.replace(/\n/g,' '); does not modify str var since strings are immutable. Then, you do not need the anchors ^ and $, as the date is inside the string, it is not equal to the string itself. Also, you need to match days from 1 to 31, but [01][0-9] only matches from 00 to 19.

You may consider using

var str = "I need the only the    date 04-Jun-2017\n"
var date = str.match(/\b\d{1,2}-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-\d{4}\b/i);
if (date) {
  console.log(date[0]);
}

The anchors are replaced with word boundaries \b and the day part is changed into \d{1,2} matching any 1 or 2 digits. The i modifier will make the pattern case insensitive.

Upvotes: 3

Related Questions