5

I have a very easy question. Unfortunately, I can't find the answer.

I just made 2 simple input functions

Input 1:<br /><input type="text" id="i1" name="i1" />
Input 2:<br />
<input type="text" id="i2" name="i2" />

When changing input 1, I want to let appear the result in input 2. Also I want some characters being replaced and I want to make the characters lower case (in order to use it as an url).

So I made the following jQuery code:

$("#i1").keyup(function() {
var ptitle = $("#i1").val();
$("#2").val(ptitle.replace(" ", "-").toLowerCase());
});

This works good, except when I type a string that has multiple times the same character to replace. Then it only replaces the first time.

For example: When I type in input 1: 'About this company' it will result in input 2: 'about-this company'. It should be: 'about-this-company'. Does anyone knows what is going wrong in my jQuery code?

user229044
  • 232,980
  • 40
  • 330
  • 338
J.2
  • 138
  • 1
  • 2
  • 8

3 Answers3

9

Something like this:

$("#i1").keyup(function() { 
    var ptitle = $(this).val(); 
    $("#i2").val(ptitle.replace(/\s/g, "-").toLowerCase()); 
});
jerone
  • 16,206
  • 4
  • 39
  • 57
  • Wow, that was extreme fast. And you did solve my problem. Thank you very much! – J.2 Jul 28 '10 at 19:58
  • No problem, I see multiple people have the same answer. I changed the `$("#i2")` with the `i` in it (accourding to your example) and I added the regexp `/\s/g` instead of your `" "`. – jerone Jul 28 '10 at 20:01
  • 1
    Be sure that you mean \s instead of ' ', the difference is that \s represents all whitespace [\f\n\r\t\v\u00A0\u2028\u2029]. This may be fine with you, but I'd be remiss if I didn't mention it. – Marc Jul 28 '10 at 20:04
2

This is because replace requires a global flag to replace multiple instances.

Try this

$("#i1").keyup(function() { var ptitle = $("#i1").val(); 
       $("#2").val(ptitle.replace(/ /g, "-").toLowerCase()); 
});

Here's a pretty close question to yours with a good answer:
Replacing spaces with underscores in JavaScript?

Community
  • 1
  • 1
Marc
  • 9,254
  • 2
  • 29
  • 31
0

this works for me

$(function(){
  $("#i1").keyup(function() {
    var ptitle = $("#i1").val();
    $("#i2").val( ptitle.replace(/ /g,"-").toLowerCase() );
  });
});
Ties
  • 5,726
  • 3
  • 28
  • 37