修剪除空格以外的其他字符? (trim() 用于可变字符)

Trimming other characters than whitespace? (trim() for variable characters)

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

这是我的用例:

输入:

university-education
-test
football-coach
wine-

输出:

university-education
test
football-coach
wine

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

^-*|-*$

解释:

^ - 字符串的开头
-* 零次或多次匹配破折号
| - 或
-* - 匹配破折号零次或多次
$ - 字符串结尾

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----'));

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

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

这里的'trim'功能不足。您可以在 '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"
    ]
*/