最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

I'm trying to do two things:

  1. Remove spaces at the end of a string
  2. 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:

  1. Remove spaces at the end of a string
  2. 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 badges
Add a ment  | 

4 Answers 4

Reset to default 3

try 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.

发布评论

评论列表(0)

  1. 暂无评论