Remove the spaces in the string, and use regularization to remove the spaces before, after, before and after, and in the middle according to different requirements.

Regular small tips:

Regular Expression - Modifiers

g global - match globally

Regular Expressions - Metacharacters 

^ Matches the beginning of the input string.
* Matches the preceding subexpression zero or more times.
$ Matches the end of the input string.
\s

Matches any whitespace character, including spaces, tabs, form feeds, and so on.

+

Matches the preceding subexpression one or more times.

Regex - operator precedence 

Regular expressions are calculated from left to right, those with the same priority are calculated from left to right, and those with different priorities are calculated first and then low. The following table illustrates the order of precedence of the various regular expression operators, from highest to lowest:

\ Escapes
(), (?:), (?=), [] parentheses and square brackets
*, +, ?, {n}, {n,}, {n,m} qualifier
^, $, \ any metacharacter, any character Anchors and sequences (ie: position and order)
| Substitution, "or" operator
characters have higher precedence than substitution operators, such that "m|food" matches "m" or "food". To match "mood" or "food", use parentheses to create a subexpression, resulting in "(m|f)ood".

 To remove spaces:

    function deleSpac(str,direction) { // 1 串的模板 2 清除哪边空格
            let Reg = '';
            switch(direction) {
                case 'left' : // 去除左边
                    Reg = /^[\s]+/g;
                    break;
                case 'right' : // 去除右边
                    Reg = /([\s]*)$/g;
                    break;
                case 'both' : // 去除两边
                    Reg = /(^\s*)|(\s*$)/g
                    break;
                default :   // 没传默认全部,且为下去除中间空格做铺垫
                    Reg = /[\s]+/g;
                    break;
            }
            let newStr = str.replace(Reg,'');
            if ( direction == 'middle' ){
                let RegLeft = str.match(/(^\s*)/g)[0]; // 保存右边空格
                let RegRight = str.match(/(\s*$)/g)[0]; // 保存左边空格
                newStr = RegLeft + newStr + RegRight; // 将空格加给清完全部空格后的字符串
            }
            return newStr;
        }

Execution method:

    let str='  asdn  owi w   '
    
    console.log(deleSpac(str,'left')); //左
    console.log(deleSpac(str,'right')); //右
    console.log(deleSpac(str,'both')); //两边
    console.log(deleSpac(str,)); //全部
    console.log(deleSpac(str,'middle')); //中间

Console output:

 

 

Guess you like

Origin blog.csdn.net/qq_56715703/article/details/131121970