admin管理员组

文章数量:1405153

I am getting some content into a website and need to process the entry titles so that they don't contain any dates. More specifically, a string such as "Lorem ipsum 30-08-2011 dolor" needs to bee "Lorem ipsum dolor". I have to take into account dates such as: 30-08-2011, 30.08.2011 and 30/08/2011.

After searching around I tried something like this, but it doesn't work:

str.replace(/^(0?[1-9]|[12][0-9]|3[01])[\/\-\.](0?[1-9]|1[012])[\/\-\.]\d{4}$/, '');

Any help is greatly appreciated. Thanks!

I am getting some content into a website and need to process the entry titles so that they don't contain any dates. More specifically, a string such as "Lorem ipsum 30-08-2011 dolor" needs to bee "Lorem ipsum dolor". I have to take into account dates such as: 30-08-2011, 30.08.2011 and 30/08/2011.

After searching around I tried something like this, but it doesn't work:

str.replace(/^(0?[1-9]|[12][0-9]|3[01])[\/\-\.](0?[1-9]|1[012])[\/\-\.]\d{4}$/, '');

Any help is greatly appreciated. Thanks!

Share Improve this question edited Oct 3, 2012 at 8:39 user447356 asked Oct 3, 2012 at 8:38 radu.luchianradu.luchian 3791 gold badge6 silver badges21 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4

Remove the ^ and $ if you want to match the pattern inside a string. Your current regex will only match a string that only contains a date.

Also, if you want to remove multiple dates from a string, you need to use a global regex, by adding a g after the closing /.

str.replace(/(0?[1-9]|[12][0-9]|3[01])[\/\-\.](0?[1-9]|1[012])[\/\-\.]\d{4}/g, '');

str.replace(/\d{1,2}[\-|\.|\/]\d{1,2}[\-|\.|\/]\d{2,4}/g, "")

http://jsfiddle/cJCBE/

function checkDate(date) {
  var re = /^\d{2}[.\/-]\d{2}[.\/-]\d{4}$/;
  return re.test(date);
}

本文标签: javascriptRemoving date from stringStack Overflow