Home  >  Article  >  Web Front-end  >  How to remove spaces from string in es6

How to remove spaces from string in es6

青灯夜游
青灯夜游Original
2022-05-05 11:42:362910browse

Two methods to remove spaces in a string: 1. Use trim() to remove spaces at the beginning and end of the string, the syntax is "String object.trim()". 2. Using replace(), you can use regular expressions to remove all spaces in the string. The syntax is "String object.replace(/\s/g,"")".

How to remove spaces from string in es6

The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.

es6 Method to remove spaces in a string

1. Use trim()--to remove spaces at the beginning and end of a string The trim() method is used to remove the leading and trailing whitespace characters of a string. The whitespace characters include: spaces, tabs, newlines and other whitespace characters.

Note:

The trim() method does not change the original string.
  • The trim() method is not applicable to null, undefined, Number types.
  • Example:
  • var str = " hello  world "
    console.log("原字符串:"+str+"!");
    var newStr=str.trim();
    console.log("新字符串:"+newStr+"!");

How to remove spaces from string in es62. Use replace()--to remove all spaces in the string

Thereplace() method is used to replace some characters with other characters in a string, or replace a substring that matches a regular expression.

If you want to use replace() to remove spaces, you can use regular expressions to match the spaces in the string, and then replace them with empty characters

''

to remove the spaces.

var str = " hello  world "
console.log("原字符串:"+str+"!");
var newStr=str.replace(/\s/g,"");
console.log("新字符串:"+newStr+"!");

[Related recommendations: How to remove spaces from string in es6javascript video tutorial

,

web front-end

The above is the detailed content of How to remove spaces from string in es6. 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