Replace spaces in the input box in JS, in dealing with the needs of a very common form of an action to prevent the user's operating habits cause data anomalies, to ensure the safety parameter passing.
NO.1
name.replace(" ","");
The above-described method is very simple alternative, but there are two weaknesses:
1. Alternatively only a single space in English or Chinese space (full);
2. Alternatively only the first occurrence of the current string.
NO.2
name.replace(new RegExp(/( )/g),"");
By the above mentioned process is a positive match, all can be replaced, but there is still a weakness:
1. Alternatively only one kind of English spaces or spaces in Chinese (full angle).
NO.3
name.split(" ").join("");
The above-described method is separated and then incorporated by the character, replace all possible, but still has a weakness:
1. Alternatively only one kind of English spaces or spaces in Chinese (full angle).
NO.4
name.replace(/(^\s*)|(\s*$)/g,"");
By the above mentioned process is a positive match, the space can be replaced in English or Chinese, but has a weakness:
1. Replace only spaces inclusive, the intermediate space does not work string.
Ultimate Shazhao
name.replace(/\s+/g,"");
By the above mentioned process is a positive match, the space can be replaced in English or Chinese, and replace all.
[Note] JS and no so-called replaceAll method, the author test results "undefined", does not recognize the page. Of course, there is a roundabout solution may be, it is carried out replaceAll prototype method according to replace the function of rewrite:
String.prototype.replaceAll = function(reallyDo, replaceWith, ignoreCase) { if (!RegExp.prototype.isPrototypeOf(reallyDo)) { return this.replace(new RegExp(reallyDo, (ignoreCase ? "gi": "g")), replaceWith); } else { return this.replace(reallyDo, replaceWith); } }
Reproduced please specify: Homecoming >> JS replace all spaces