0

I am wanting to replace 1 word with another with JavaScript, the code i have is working as below:

$('#test').contents().filter(function() {
    return this.nodeType == 3
}).each(function(){
    this.textContent = this.textContent.replace('microsoft', 'Hi I am
replace'),('bob', 'bobart')    
});

The code works for the first instance and will replace Microsoft but will not change Bob, how can I add multiple words to be replaced into this?

Thank you

1
  • 2
    You have a syntax error: ,('bob'... should be .replace('bob'... Commented Mar 9, 2015 at 13:34

2 Answers 2

2

Use chaining of replace using .replace('x','y').replace('a','b'):

his.textContent.replace('microsoft', 'Hi I am replace').replace('bob', 'bobart')   
Sign up to request clarification or add additional context in comments.

Comments

0

You can do it like this:

var replacers = {"to_be_replaced_1": "by_this_1","to_be_replaced_2":"by_this_2"},
    stringToBeReplaced = "some text to_be_replaced_1";

$.each(replacers ,function(replaceable, replacer){
   stringToBeReplaced.replace(replaceable, replacer);
});

Comments

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.