1

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

asked Jan 31, 2011 at 17:26

4 Answers 4

13

To do a global replace, you need to use a regex with the g flag:

var myval = $(this).val().replace(/ /g, "_");
answered Jan 31, 2011 at 17:28
Sign up to request clarification or add additional context in comments.

1 Comment

Good Job @lonesomeday
3

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

answered Jun 10, 2012 at 11:36

1 Comment

Worked flawlessly, thanks for the snippet & neat JS
2

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.

answered Jan 31, 2011 at 17:31

Comments

0

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

Rohit Suthar
3,6282 gold badges48 silver badges49 bronze badges
answered Dec 27, 2013 at 11:15

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.