Home > Web Front-end > JS Tutorial > 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

青灯夜游
Release: 2021-06-15 17:51:06
Original
6808 people have browsed it

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)
};
Copy after login

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+$/, '');
};
Copy after login

Improve and simplify it, and it looks more elegant.

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

[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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template