且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用JavaScript和正则表达式删除空格。

更新时间:2023-02-17 22:52:18

试试这个:

Try this:
var withSpaces = prompt('Enter a number please:');
var withoutSpaces = withSpaces.replace(/\s/g, '');



之后 g > / \s / 表示全局匹配,这意味着它将删除所有空白。如果你删除 g 那么它只会删除第一个空格/制表符/换行符。



在线演示: http://jsfiddle.net/ProgramFOX/RwF9Y/ [ ^ ]


The g after /\s/ means global match, that means that it will remove all whitespace. If you remove the g then it will only remove the first space/tab/newline.

Online demo: http://jsfiddle.net/ProgramFOX/RwF9Y/[^]


您好,



***分享你的代码,但是以通用方式这是你的查询的解决方案



Hello ,

It is better to share your code but in a generic way this is the solution for your query

val = val.replace(/\s/g, '')





其中g代表一般





***的:)如果你回信请写回来需要任何支持。



Where g stands for general


All the best:)Pls write back if you need any support.


尝试

Try
var str = "2365 2365"
str = str.replace(/\s+/g, '');