开发者

javascript replace characters

开发者 https://www.devze.com 2023-03-29 07:49 出处:网络
I want to 开发者_运维百科replace all occurent of \"-\", \":\" characters and spaces from a string that appears in this format:

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, "");


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

精彩评论

暂无评论...
验证码 换一张
取 消