admin管理员组文章数量:1426637
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.
本文标签: javascriptRegex to check if last character is hyphen ()if not add itStack Overflow
版权声明:本文标题:javascript - Regex to check if last character is hyphen (-), if not add it - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745479901a2660130.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论