I have 2 textboxes one called 'title' one called 'url'. Using jquery on .blur() I'm copying the value of the 'title' into the 'url' value and I'm replacing blank spaces with underscores, but for some reason it only replaces the first blank space and not all of them: Here's the code:
$("#title").blur(function(){
var myval = $(this).val().replace(" ", "_");
$("#url").val(myval);
});
What am I doing wrong?
Thanks in advance
4 Answers 4
To do a global replace, you need to use a regex with the g flag:
var myval = $(this).val().replace(/ /g, "_");
1 Comment
Here is my replace function! I hope you will like it.
function myReplaceMethod(str,find,replace_with){
while (str.indexOf(find) !== -1 ){
from = str.indexOf(find);
to = from + find.length;
str = str.substr(0,from)+replace_with+str.substr(to, str.length-to);
}
return str;
}
Example of use:
str = myReplaceMethod(str,"example1",""); // nothing
str = myReplaceMethod(str,"example2","new text here"); //for new text
For further information visit my blog : http://www.phpdevblog.eu/2012-06/jquery/javascript-replace-method-not-working-properly.html
1 Comment
You need to use Regular Expressions to find ALL occurrences of the string you want to replace (space, in this case).
$("#title").blur(function(){
var myval = $(this).val().replace(/ /g, "_");
$("#url").val(myval);
});
the "g" means "global," so it will keep searching even after the first match.
Comments
Best way is just to use " in stead of '.
discount = item.val().replace(",", ".");
if you insert 8,09 this will be converted to 8.09