Home>Article>Web Front-end> How to remove spaces from the beginning and end of a string in javascript

How to remove spaces from the beginning and end of a string in javascript

青灯夜游
青灯夜游 Original
2021-06-15 17:50:54 6693browse

Method: 1. Use the "substring(Math.max(this.search(/\S/),0),this.search(/\S\s*$/) 1)" statement; 2 , use the "replace(/^\s /,'').replace(/\s $/,'')" statement.

How to remove spaces from the beginning and end of a string in javascript

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

##javascript Remove spaces from the beginning and end of the string

1. substring() intercepts all characters from the index of the first non-space character to the index of the last non-space character, and returns the intercepted characters String

String.prototype.trimOne = function () { return this.substring(Math.max(this.search(/\S/), 0), this.search(/\S\s*$/)+1) };

2. The replace() method replaces all the spaces at the beginning of the string with an empty string, and then replaces all the spaces at the end of the character bed with an empty string

String.prototype.trimTwo = function () { return this.replace(/^\s+/, '').replace(/\s+$/, ''); };

Improve and simplify it, and it looks more elegant.

String.prototype.trimThree = function () { return this.replace(/^\s+|\s+$/g, '') };

[Related recommendations:

javascript learning tutorial]

The above is the detailed content of How to remove spaces from the beginning and end of a string in 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