【问题标题】:Trimming other characters than whitespace? (trim() for variable characters)修剪除空格以外的其他字符? (trim() 用于可变字符)
【发布时间】:2020-07-24 19:55:27
【问题描述】:

有没有一种简单的方法可以替换字符串开头和结尾的字符,而不是中间的字符?我需要修剪破折号。我知道trim() 存在,但它只修剪空白。

这是我的用例:

输入:

university-education
-test
football-coach
wine-

输出:

university-education
test
football-coach
wine

【问题讨论】:

标签: javascript node.js ecmascript-6 trim


【解决方案1】:

您可以将String#replace 与正则表达式一起使用。

^-*|-*$

说明:

^ - 字符串的开头
-* 匹配短划线零次或多次
| - 或
-* - 匹配短划线零次或多次
@ 987654328@ - 字符串结束

function trimDashes(str){
  return str.replace(/^-*|-*$/g, '');
}
console.log(trimDashes('university-education'));
console.log(trimDashes('-test'));
console.log(trimDashes('football-coach'));
console.log(trimDashes('--wine----'));

【讨论】:

    【解决方案2】:

    我建议使用the trim function of lodash。它完全符合您的要求。它有第二个参数,允许您传递应该修剪的字符。在您的情况下,您可以像这样使用它:

    trim("-test", "-");

    【讨论】:

      【解决方案3】:

      这里的“修剪”功能是不够的。您可以在 'replace' 函数中使用 'RegEx' 来弥补这一差距。

         let myText = '-education';
         myText = myText.replace(/^\-+|\-+$/g, ''); // output: "education"
      

      在数组中使用

        let myTexts = [
          'university-education',
          '-test',
          'football-coach',
          'wine',
        ];
      
        myTexts = myTexts.map((text/*, index*/) => text.replace(/^\-+|\-+$/g, ''));
        /* output:
          (4)[
            "university-education",
            "test",
            "football-coach",
            "wine"
          ]
        */
      
      /^\   beginning of the string, dashe, one or more times
      |     or
      \-+$  dashe, one or more times, end of the string
      /g    'g' is for global search. Meaning it'll match all occurrences.
      

      示例:

      const removeDashes = (str) => str.replace(/^\-+|\-+$/g, '');
      
      /* STRING EXAMPLE */
      const removedDashesStr = removeDashes('-education');
      console.log('removedDashesStr', removedDashesStr);
      // ^^ output: "removedDashesStr education"
      
      let myTextsArray = [
        'university-education',
        '-test',
        'football-coach',
        'wine',
      ];
      
      /* ARRAY EXAMPLE */
      myTextsArray = myTextsArray.map((text/*, index*/) => removeDashes(text));
      console.log('myTextsArray', myTextsArray);
      /*^ outpuut:
          myTextsArray [
            "university-education",
            "test",
            "football-coach",
            "wine"
          ]
      */

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多