0

Let say the variable name is

var name = "Stack overflow is great";

I want to change it to

var name = "Stack-overflow-is-great";

I did this

name.replace(/ /g, '-');

and here is the result

var name = "Stack-overflow-is-great-";

There is an extra dash at the end, how do i prevent from the last dash to appear in my string?

7
  • 3
    make sure you dont have any spaces at the end. Just as a work around you can do name.replace(/-$/g,''); Commented Aug 17, 2016 at 5:09
  • 1
    try replace(/\s/g, "-") Commented Aug 17, 2016 at 5:09
  • 1
    for me it works properly, you might be missing whitespaces which are there just trim it like name.trim().replace(/ /g, '-');. Commented Aug 17, 2016 at 5:10
  • 3
    Not reproducible with the code you provided. Commented Aug 17, 2016 at 5:12
  • 1
    Just to note, you can test regex using regex101.com - Input your string and then you can see exactly how regex will react to your string. Commented Aug 17, 2016 at 5:44

5 Answers 5

1

I believe, your actual input contains trailing spaces, because your example works ok.

Remove trailing space with trim function as I've showed in snippet below.

var name = "Stack overflow is great ";
var newName = name.trim().replace(/ /g, '-');
console.log(newName);

Sign up to request clarification or add additional context in comments.

1 Comment

Stack Overflow's snippet window has a handy console mirror, so please use console.log() rather than alert() for this sort of thing.
0

Using concat() function you can add expression at the end of the string .

(function(){
var name = "Stack overflow is great";
name=name.replace(/ /g, '-');
var name=name.concat(expression);

}());

Comments

0

You can use endWith to check if your name has space at the End.

var name = "Stack overflow is great ";
if(name.endsWith(" ")){
 name = name.substring(0, name.length -1);
 }
console.log(name.replace(/ /g, '-'));

Comments

0

You have to assign the return value from the replace() function to a variable. The replace() function does not change the String object it is called on. It simply returns a new string.

    var name  = "Stack overflow is great";

    name = name.replace(/ /g, '-');

    console.log(name);

1 Comment

this is just similar to the question asked
0

One quick solution is to exclude the last dash.

            var name = "Stack overflow is awsome "
            name = name.replace(/ /g,'-');
            console.log(name);
            var pos = name.lastIndexOf('-');
            console.log(pos);
            name = name.substring(0,pos);

            console.log(name);

1 Comment

Did you test this on cases where there isn't a dash at the end of the string?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.