-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
  • 260
  • 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
  • 2,811
  • 3
  • 20
  • 45
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
  • 64,240
  • 8
  • 67
  • 88
  • @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,366
  • 6
  • 34
  • 49
1

try like this:

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