Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: replace() in html()

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/

like image 365
Martin Avatar asked Apr 27 '14 16:04

Martin


People also ask

How do you replace content in HTML?

Use . replace() method on HTML element and replace it with the new HTML Document(eg.. $('html').

What is replacing jQuery?

JavaScript: Native JavaScript is one of the most common alternatives to jQuery.

What does $() mean in jQuery?

In jQuery, the $ sign is just an alias to jQuery() , then an alias for a function. This page reports: Basic syntax is: $(selector).action() A dollar sign to define jQuery. A (selector) to "query (or find)" HTML elements.


1 Answers

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

like image 133
Oriol Avatar answered Oct 02 '22 11:10

Oriol