-1

I have this code

$("#title").keyup(function(){
var titleval = $("#title").val();

var res = titleval.replace(" ", "-");

$("#newsurl").val(res);

});

to replace spaces into dash to get URL like this

wordone-wordtow-wordthree

but i have problem with this code it's just replace first space like this

wordone-wordtow wordthree

How can i solve this problem

Mahmoud Samy
  • 270
  • 2
  • 11

4 Answers4

3

You need to do a global match, you can do this with a regex

var res = titleval.replace(/\s/g, "-");

Though String.prototype.replace does support having flags passed, this is deprecated in firefox and already doesn't work in chrome/v8.

Joey Ciechanowicz
  • 3,345
  • 3
  • 24
  • 48
2

Alternate method (if regex is not mandatory) could be to split and join

var res = titleval.split(" ").join("-");

or

var res = titleval.split(/\s+/).join("-");
gurvinder372
  • 66,980
  • 10
  • 72
  • 94
  • @Guru, Why `.split` over `.replace` ? – Rayon Apr 12 '16 at 11:29
  • @RayonDabre yes agree, maybe this is truely the most trivial scenario to use split and join over replace. This is just an alternate method to do the same job, I guess. – gurvinder372 Apr 12 '16 at 11:31
1

Use regex with global flag

titleval.replace(/\s/g, "-");
isvforall
  • 8,768
  • 6
  • 35
  • 50
1

try like this:

$("#title").keyup(function(){
 var titleval = $("#title").val();
 var res = titleval.replace(/\s+/g, '-');
 $("#newsurl").val(res);
});
Sumanta736
  • 695
  • 3
  • 10