我正在尝试做两件事:
- 删除字符串末尾的空格
- 如果破折号(-)不是字符串的最后一个字符,则将其添加到字符串的末尾
test = test.replace(/-\s*$/, "-");
我并不一定要使用正则表达式,只是想寻找最简洁的方法来完成这个任务。谢谢 :)
test = test.replace(/-\s*$/, "-");
我并不一定要使用正则表达式,只是想寻找最简洁的方法来完成这个任务。谢谢 :)
test = test.replace(/-?\s*$/, "-");
^
|== Add this
test -
,它会返回 test -
吗? - VisioNstr.replace(/[-\s]*$/, '-');
测试:
"test" --> "test-"
"test-" --> "test-"
"test- " --> "test-"
"test -" --> "test-"
"test - " --> "test-"
不需要正则表达式。尝试使用:
if(yourStr.slice(-1) !== "-"){
yourStr = yourStr + "-";
} else{
//code if hyphen is last char of string
}
注意:将yourStr
替换为您想要使用的字符串变量。
test.replace(/(-?\s*)$/, "-")
在监视窗口中可以工作,但在我的代码中test = test.replace(/(-?\s*)$/, "-")
只是将 test 设置为原来的值,并没有在末尾添加连字符。 - bflemi3