javascript 替换字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7098496/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 22:58:13  来源:igfitidea点击:

javascript replace characters

javascriptreplace

提问by mustapha george

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

回答by Gabi Purcaru

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

你很接近: "YYYY-MM-DD HH:MM:SS".replace(/:|-/g, "")

回答by Rocket Hazmat

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

/:-/g是指":" followed by "-"。如果您将字符放入其中,[]则表示":" or "-".

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

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

如果要删除空格,请添加\s到正则表达式。

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

回答by zzzzBov

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 \spattern 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).

在其中,我添加了\s匹配空格字符的模式,例如空格和制表符\t(不确定是否需要制表符和换行符,所以我使用制表符并跳过了换行符)。

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

似乎您已经猜到您想要global 匹配,它允许正则表达式不断替换它找到的匹配。

回答by FishBasketGordo

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