javascript 使用javascript删除字符串中的空格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11280812/
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
remove spaces in string using javascript
提问by Anu K. C.
I need to do some functions on some text field contents before submitting the form, like checking the validity of the customer registeration code, having the customer name as his code in customers table appending an incrementing number.
在提交表单之前,我需要对某些文本字段内容执行一些功能,例如检查客户注册代码的有效性,将客户名称作为客户表中的代码附加一个递增数字。
I don't want to do it after the form is submitted becuase I need it to be displayed in the code field before submitting the form.
我不想在提交表单后执行此操作,因为我需要在提交表单之前将其显示在代码字段中。
My code:
我的代码:
function getCode(){
var temp = document.getElementById("temp").value ;
var d = parseInt(document.getElementById("temp").value) + 1;
document.getElementById("customernumber").value = d;
document.getElementById("code").value = document.getElementById("name").value+"-"+ d;
}
It all works fine, but the last line of code developed the code WITH the spaces between the code.
一切正常,但最后一行代码开发了代码之间的空格。
回答by sachleen
A couple ways to remove spaces...
删除空格的几种方法...
Using regex: string.replace(/ /g,'');
使用正则表达式: string.replace(/ /g,'');
Splitting the string by spaces and combining the array with no delimiter:
按空格拆分字符串并组合不带分隔符的数组:
string.split(' ').join('');
string.split(' ').join('');
回答by Anu K. C.
var str = "ab cd ef gh ";
str = str.replace(/\s+/g,"");