简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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