remove spaces in string in js

This article was originally published on my blog . If you want to know more front-end knowledge, welcome to visit my personal blog: Fat Cai

In the process of front-end development, we often encounter the need to format the input string. This article mainly introduces how to remove the spaces of the string through js. This article provides three types to remove the spaces of the string.

1. Remove the leading and trailing spaces of the string

let str= ' 去除头部和尾部空格  ';
let result  = str.replace(/^[" "||" "]*/,"").replace(/[" "|" "]*$/,"");
console.log('get result:',result);

//get result:去除头部和尾部空格

2. Remove all spaces in the string

let str= ' 去除字符串中的所有空格  qckg  ';
let result  = str.replace(/\s/g,'');
console.log('get result:',result);

//get result:去除字符串中的所有空格qckg

3. Remove spaces at the end of the string

let str= ' 去除字符串结尾处的空格  qckg  ';
let result  = str.replace(/(\s*$)/g,"");
console.log('get result:',result);

//get result: 去除字符串结尾处的空格  qckg

Guess you like

Origin blog.csdn.net/chf1142152101/article/details/127533000