Home>Article>Web Front-end> How to remove spaces before and after a string in es6
Two methods to remove leading and trailing spaces: 1. Directly use trim() to remove the spaces at the beginning and end of the string, the syntax is "str.trim()"; 2. First use trimStart() to remove the leading spaces character, and then use trimEnd() to eliminate the trailing space character, the syntax is "str.trimEnd(str.trimStart())".
The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.
es6 Method to remove spaces before and after 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.var str = " hello world " console.log("原字符串:"+str+"!"); var newStr=str.trim(); console.log("新字符串:"+newStr+"!");
2. Use trimStart() trimEnd()--remove the beginning and end of the string The behavior of the space character
trimStart() and trimEnd() is consistent with trim(). trimStart() eliminates spaces at the head of the string, and trimEnd() eliminates spaces at the end. They return new strings and do not modify the original strings.
const s = ’ abc '; s.trim() // “abc” s.trimStart() // "abc " s.trimEnd() // " abc"In the above code, trimStart() only eliminates the leading spaces and retains the trailing spaces. trimEnd() behaves similarly. If you want to remove the spaces at the beginning and end of the string, first use trimStart() to remove the leading spaces, and then use trimEnd() to remove the trailing spaces.
var str = " hello world " console.log("原字符串:"+str+"!"); var newStr=str.trimEnd(str.trimStart()); console.log("新字符串:"+newStr+"!");
Description:
In addition to the space bar, the trimStart() and trimEnd() methods work on the tabs at the head (or tail) of the string. Invisible whitespace characters such as keys and newlines are also valid.
javascript video tutorial
,web front-end】
The above is the detailed content of How to remove spaces before and after a string in es6. For more information, please follow other related articles on the PHP Chinese website!