Javascript remove spaces (first and last, between words, all) with regular expression

Lionsure 2020-05-22 Original by the website

In the Web design process, especially when submitting forms, it is often necessary to use javascript to remove front and back spaces (or first and last spaces or left and right spaces). Replace() function (method) is usually used to remove spaces in javascript, and regular expressions are used to match spaces. It is often achieved by a simple code.

In addition to removing the spaces before and after the text, sometimes you must also remove all spaces in the text, or remove blank lines, etc., and then introduce their code implementation methods by example.

 

I. Javascript remove spaces at beginning and end of string (i.e. How to remove front and back space in javascript) with regular expression

The user enters text, and there may be spaces before and after the text, and these spaces have no practical effect. At this time, it should be removed to avoid being unable to retrieve records due to spaces. The code implementation is as follows:

String.prototype.trim = function () { return this.replace(/(^\s*)|(\s*$)/g, ""); }

 

Call:

var text = " How to remove leading and trailing spaces in javascript ";
       text.trim();

 

II. Javascript remove spaces at beginning of string (i.e. Javascript remove left space) with regular expression

String.prototype.lefttrim = function () { return this.replace(/(^\s*)/g, ""); }

 

Call:

var text = " Javascript remove left space";
       text.lefttrim();

 

 

III. Javascript remove spaces from end of string (i.e. Javascript remove right space) with regular expression

String.prototype.righttrim = function () { return this.replace(/(\s*$)/g, ""); }

 

Call:

var text = "Javascript remove right space ";
       text.righttrim();

 

 

IV. Javascript remove spaces between words

String.prototype.betweenwordstrim = function () { return this.replace(/[ ]/g, " "); }

 

Call:

var text = "Javascript remove spaces between words";
       text.betweenwordstrim();

Result: Javascript remove spaces between words

 

 

V. Javascript remove all spaces with regular expression

String.prototype.alltrim = function () { return this.replace(/\s+/g, ""); }

The regular expression /\s+/g used will remove all spaces in the text (including spaces between words or letters), and also remove all line breaks, that is, all text becomes one line.

 

Call:

var text = " How to remove all spaces from string in javascript ";
       text.alltrim();

Result: Howtoremoveallspacesfromstringinjavascript

 

All the above codes pass the test and can be called directly. Just copy them between in the webage and call it according to the calling method in the example.