Home>Article>Web Front-end> How to replace spaces with javascript

How to replace spaces with javascript

藏色散人
藏色散人 Original
2021-04-27 10:24:29 6948browse

How to replace spaces in JavaScript: 1. Use "name.replace(" ","");" to replace; 2. Use "replace(new RegExp(/( )/g),""); "; 3. Use "name.split(" ").join("");" and so on.

How to replace spaces with javascript

The operating environment of this article: windows7 system, javascript version 1.8.5, Dell G3 computer.

Replacing spaces in the input box in JS is a very common operation when processing form requirements to prevent data anomalies caused by user operating habits and ensure the security of parameter transfer.

NO.1

name.replace(" ","");

The above method is a very simple replacement, but it has two weaknesses:

1. It can only replace a single English space or Chinese space (full-width) ;

2. Only the first match of the current string can be replaced.

NO.2

name.replace(new RegExp(/( )/g),"");

The above method uses regular matching and can replace all, but there is still a weakness:

1. Only English spaces or Chinese spaces can be replaced (full-width).

NO.3

name.split(" ").join("");

The above method is to separate and merge by characters, which can replace all, but there is still a weakness:

1. It can only replace English spaces or One of Chinese spaces (full width).

NO.4

name.replace(/(^\s*)|(\s*$)/g,"");

The above method uses regular matching and can replace English or Chinese spaces, but there is a weakness:

1. It can only replace the leading and trailing spaces. Does not work on spaces in the middle of the string.

Ultimate Killing Move

name.replace(/\s+/g,"");

The above method is through regular matching, which can replace English or Chinese spaces and replace them all.

[Note] There is no so-called replaceAll method in JS. The author's test result is "undefined" and cannot be recognized on the page. Of course, there is also a workaround, which is to rewrite the prototype of the replaceAll method based on the function of replace:

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); } }

[Recommended learning:javascript advanced tutorial]

The above is the detailed content of How to replace spaces with javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn