Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Is there an easy way to replace characters at the beginning and end of a string, but not in the middle? I need to trim off dashes. I know trim() exists, but it only trims whitespace.

Here's my use case:

Input:

university-education
-test
football-coach
wine-

Output:

university-education
test
football-coach
wine
like image 661
userjmillohara Avatar asked Oct 27 '25 07:10

userjmillohara


1 Answers

You can use String#replace with a regular expression.

^-*|-*$

Explanation:

^ - start of the string
-* matches a dash zero or more times
| - or
-* - matches a dash zero or more times
$ - end of the string

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----'));
like image 164
Unmitigated Avatar answered Oct 28 '25 21:10

Unmitigated



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!