检查最后一个字符是否为连字符(-),如果不是则添加它

Regex to check if last character is hyphen (-), if not add it

本文关键字:如果不 添加 字符 最后一个 是否 连字符 检查      更新时间:2023-09-26

我想做两件事:

  1. 删除字符串末尾的空格
  2. 如果连字符(-)不是字符串中的最后一个字符,则将其添加到字符串的末尾

我的尝试,它只替换末尾的连字符和空格:

test = test.replace(/-'s*$/, "-");

我不设置正则表达式只是寻找最干净的方式来做到这一点。谢谢:)

试试这个,在这里工作http://jsfiddle.net/dukZC/:

test.replace(/(-?'s*)$/, "-");

将连字符设置为可选的,这样两种情况都可以使用:

test = test.replace(/-?'s*$/, "-");
                      ^
                      |== Add this

如果你不关心最后连字符的数量,那么这个解决方案可能很适合你:

str.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替换为您想要使用的字符串变量

相关文章: