I have a string in JavaScript like var s="test - test1"
and sometimes s=" - test1"
and sometimes just " -"
. I want to remove the space and hyphen only if it’s present at the start and end of the string. Meaning, we should not do anything for the 1st case s="test - test1"
.
Expected Result:
var s="test - test1"
result should be "test - test1"
var s=" - test1"
result should be "test1"
" -"
result should be ""
Could you guys help me on this?
3
Answers
I assume you want to remove all spaces with the following hyphens, then just replace it with this method
.replace(/ -/g,'')
.A regex-only solution (try-its were modified a bit to avoid messing with line breaks):
Try it on regex101.com.
…or, using
.replace()
:Try it on regex101.com.