Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery multiple character replace

Tags:

jquery

replace

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?

like image 852
J.2 Avatar asked Jul 28 '10 19:07

J.2


2 Answers

Something like this:

$("#i1").keyup(function() { 
    var ptitle = $(this).val(); 
    $("#i2").val(ptitle.replace(/\s/g, "-").toLowerCase()); 
});
like image 95
jerone Avatar answered Nov 08 '22 23:11

jerone


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?

like image 35
Marc Avatar answered Nov 09 '22 00:11

Marc