这里的“修剪”功能是不够的。您可以在 '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"
]
*/