I'm trying to do two things:
- Remove spaces at the end of a string
- If a hyphen (-) is not the last character in the string then add it to the end of the string
My attempt, which only replaces hyphens and spaces at the end is:
test = test.replace(/-\s*$/, "-");
I'm not set on regex just looking for the cleanest way to do this. Thank you :)
I'm trying to do two things:
- Remove spaces at the end of a string
- If a hyphen (-) is not the last character in the string then add it to the end of the string
My attempt, which only replaces hyphens and spaces at the end is:
test = test.replace(/-\s*$/, "-");
I'm not set on regex just looking for the cleanest way to do this. Thank you :)
Share Improve this question asked Mar 20, 2014 at 18:37 bflemi3bflemi3 6,79021 gold badges95 silver badges158 bronze badges4 Answers
Reset to default 3try this, working here http://jsfiddle/dukZC/:
test.replace(/(-?\s*)$/, "-");
Make the hyphen optional and it'd work for both the cases:
test = test.replace(/-?\s*$/, "-");
^
|== Add this
If you do not care about the amount of hyphens in the end then this solution might work well for you:
str.replace(/[-\s]*$/, '-');
TESTS:
"test" --> "test-"
"test-" --> "test-"
"test- " --> "test-"
"test -" --> "test-"
"test - " --> "test-"
No need for regex. Try:
if(yourStr.slice(-1) !== "-"){
yourStr = yourStr + "-";
} else{
//code if hyphen is last char of string
}
Note: replace yourStr
with the variable with the string you want to use.