1

I'm trying to do a string replace in a textarea after the user has entered their content and nothing I've tried is working. Any help would be greatly appreciated. This is where I am:

<textarea id="field_id_29"></textarea>

$("#field_id_29").bind("change keyup input",function(){
     var text = $("#field_id_29").val();
     text = text.replace(/source/g,"www")
     $("#field_id_29").val(text);
});

I need to replace www-source with www.

jsFiddle is here: http://jsfiddle.net/6RNY2/

4 Answers 4

11

Try this,

$("#field_id_29").change(function(){
    var text = $(this).val();
    var regexp = /www-source/gi;
    if ( text.match(regexp) ){      
        text = text.replace(/www-source/g,"www");
        return $(this).val(text);
    }
    return false;
});

When the field changes we grab the value, compare if against a regular expression and if we have a match we replace the text and we are done, otherwise we just return.

Sign up to request clarification or add additional context in comments.

2 Comments

You already defined regexp, why don't you reuse variable on replace?
it changes the position of the cursor to the end of the text if the change happens at the start or in the middle :(
2

jsfiddle

        $("#field_id_29").bind("change keyup input",function(){    
            this.value= this.value.replace(/www-source/g,"www");                 
        });
​

Note: inside function this is reference of textarea so you directly use this.value instead of accessing textarea value using id.

1 Comment

* .bind("keyup") seems enough. Why not $.change though? * this.value instead of $(this).val(); care to explain what's the difference and what is faster? * I guess it would be faster without the global match /g
2

Try this,

Live Demo

[$("#field_id_29").bind("keyup", function() {
    var text = $(this).val();
    text = text.replace(/source/g, "www")
    $(this).val(text);
});​

Comments

1

Your code works, you just need to use jQuery instead of Mootools in your jsfiddle, probably also just use the change event so that it replaces the text only after the textarea has been updated

1 Comment

Geez. I see that now. Wish I could get that hour back!

Your Answer

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.