bflemi3
bflemi3

Reputation: 6790

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

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 :)

Upvotes: 3

Views: 1867

Answers (4)

user3189338
user3189338

Reputation:

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.

Upvotes: 0

VisioN
VisioN

Reputation: 145478

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-"

Upvotes: 2

bingjie2680
bingjie2680

Reputation: 7773

try this, working here http://jsfiddle.net/dukZC/:

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

Upvotes: 3

devnull
devnull

Reputation: 123668

Make the hyphen optional and it'd work for both the cases:

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

Upvotes: 2

Related Questions