6

How can I replace html parts with replace()?

<div>
    <a href="http://www.google.com">google.com</a>
</div>

JS:

var e = $("div"),
    fix = e.html().replace("google.com", "duckduckgo.com");
e.html(fix);

I guess html() is not working the same as text() ?

Test: http://jsfiddle.net/Hmhrd/

3 Answers 3

21

The problem is that .replace only replaces first occurence. If you want to replace all occurences, you must use a regular expression with a g (global) flag:

var e = $("div"),
    fix = e.html().replace(/google\.com/g, "duckduckgo.com");
e.html(fix);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
    <a href="http://www.google.com">google.com</a>
</div>

Demo

Remember you must escape special characters such as ., though. If you prefer, you can use

String.prototype.replaceAll = function(s1, s2) {
    return this.replace(
        new RegExp(  s1.replace(/[.^$*+?()[{\|]/g, '\\$&'),  'g'  ),
        s2
    );
};

var e = $("div"),
    fix = e.html().replaceAll('google.com', "duckduckgo.com");
e.html(fix);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<div>
    <a href="http://www.google.com">google.com</a>
</div>

Demo

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

1 Comment

Thanks. Saving replaceAll() just in case :)
0

Make your pattern global by using the g switch:

var e = $("div"),
fix = e.html().replace(/google.com/g, "duckduckgo.com");
e.html(fix);

jsFiddle example

This way it replaces the link and the text.

3 Comments

make your regex global, OP isn't using regex at all ;)
OH! replace() only eats regex :/
@j08691, sorry to bug you, but again, he isn't using a pattern. Don't get me wrong though
0
$("div a").attr("href", function (i, o) {
    return (/google/.test(o) ? "http://duckduckgo.com" : o)
}).html($("a", this).attr("href").substr(7))

jsfiddle http://jsfiddle.net/guest271314/6rrKs/

1 Comment

This doesn't replace link's href attribute, though.

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.