[英]Regex to check if last character is hyphen (-), if not add it
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 :) 谢谢 :)
Make the hyphen optional and it'd work for both the cases: 将连字符设置为可选,并且在两种情况下均适用:
test = test.replace(/-?\s*$/, "-");
^
|== Add this
试试这个,在这里工作http://jsfiddle.net/dukZC/ :
test.replace(/(-?\s*)$/, "-");
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. 注意:用您要使用的字符串用变量替换yourStr
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.