最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript replace characters - Stack Overflow

programmeradmin4浏览0评论

I want to replace all occurent of "-", ":" characters and spaces from a string that appears in this format:

"YYYY-MM-DD HH:MM:SS"

something like:

var date = this.value.replace(/:-/g, "");

I want to replace all occurent of "-", ":" characters and spaces from a string that appears in this format:

"YYYY-MM-DD HH:MM:SS"

something like:

var date = this.value.replace(/:-/g, "");
Share Improve this question asked Aug 17, 2011 at 19:43 mustapha georgemustapha george 6215 gold badges13 silver badges17 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 7

You were close: "YYYY-MM-DD HH:MM:SS".replace(/:|-/g, "")

/:-/g means ":" followed by "-". If you put the characters in [] it means ":" or "-".

var date = this.value.replace(/[:-]/g, "");

If you want to remove spaces, add \s to the regex.

var date = this.value.replace(/[\s:-]/g, "");

The regex you want is probably:

/[\s:-]/g

Example of usage:

"YYY-MM-DD HH:MM:SS".replace(/[\s:-]/g, '');

[] blocks match any of the contained characters.

Within it I added the \s pattern that matches space characters such as a space and a tab \t (not sure if you want tabs and newlines, so i went with tabs and skipped newlines).

It seems you already guessed that you want the global match which allows the regex to keep replacing matches it finds.

You can use either a character class or an | (or):

var date = "YYYY-MM-DD HH:MM:SS".replace(/[:-\s]/g, '');

var date = "YYYY-MM-DD HH:MM:SS".replace(/:|-|\s/g, '');
发布评论

评论列表(0)

  1. 暂无评论