简体   繁体   English

使用javascript删除字符串中的空格

[英]remove spaces in string using javascript

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. 一切正常,但最后一行代码使用代码之间的空格开发代码。

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

var str = "ab cd ef gh   ";
str = str.replace(/\s+/g,"");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM