Reputation: 6790
I'm trying to do two things:
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 :)
Upvotes: 3
Views: 1867
Reputation:
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.
Upvotes: 0
Reputation: 145478
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-"
Upvotes: 2
Reputation: 7773
try this, working here http://jsfiddle.net/dukZC/:
test.replace(/(-?\s*)$/, "-");
Upvotes: 3
Reputation: 123668
Make the hyphen optional and it'd work for both the cases:
test = test.replace(/-?\s*$/, "-");
^
|== Add this
Upvotes: 2