简体   繁体   中英

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)

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.

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.

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