sinusGob
sinusGob

Reputation: 4313

How do i replace "-" in javascript?

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?

Upvotes: 0

Views: 96

Answers (5)

Abdullah
Abdullah

Reputation: 965

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

Upvotes: 0

Sergio Marron
Sergio Marron

Reputation: 521

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

Upvotes: 0

mmushtaq
mmushtaq

Reputation: 3520

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, '-'));

Upvotes: 0

Nihar Sarkar
Nihar Sarkar

Reputation: 1299

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

}());

Upvotes: 0

userlond
userlond

Reputation: 3818

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

Upvotes: 1

Related Questions