ngplayground
ngplayground

Reputation: 21667

Javascript to replace a string inside a tag

<nav class="woocommerce-breadcrumb"><a href="http://domain.com/" class="home">Home</a> &gt; Product</nav>

Using jQuery or Javascript how would I be able to rename the word 'Product' to some other value?

var brandname = $('.tax-product_brand h1.page-title').text();
var crumb = $('.woocommerce-breadcrumb').text();
console.log(crumb);
crumb.replace("Product", brandname);

I tried the above with no luck

Upvotes: 0

Views: 898

Answers (6)

Johney
Johney

Reputation: 87

Avoid using free text. This will increase processing overhead, when you'll do DOM calculations.

It is good, if you can use tag to display the end product/page name. The html will look like:

  <nav class="woocommerce-breadcrumb">
        <a href="http://domain.com/" class="home">
            Home
        </a> 
        <span class="currentPage">>Product</span>

    </nav>

Now, you can use simple DOM operation to change the text() of expected element.

var currentPage=$(".currentPage");
$(currentPage).text('> NewText');

Upvotes: 0

ngplayground
ngplayground

Reputation: 21667

var brandname = $('.tax-product_brand h1.page-title').text();
$(".woocommerce-breadcrumb:contains('Product')").html(function(_, html) {
    return  html.replace(/(Product)/g, '<span>'+brandname+'</span>')
});

I was able to use the above to gain what I wanted whilst keeping the formatting of the a tag

Upvotes: 0

Scimonster
Scimonster

Reputation: 33409

You then need to insert your string into the DOM. As it is, you're just doing a string operation and discarding the return value.

$('.woocommerce-breadcrumb').text(crumb.replace("Product", brandname));

EDIT: As mentioned in a comment, you should use .html() instead of .text(). .text() will strip all of your HTML, i.e. your <a> tag.

Upvotes: 3

Sid
Sid

Reputation: 801

Its replaced Here is demo.

var brandname = 'My Name';

var crumb = 'My Product';

console.log(crumb);

var d= crumb.replace("Product", brandname);

alert(d);

Upvotes: 0

Curtis
Curtis

Reputation: 103428

Use .html() rather than .text() or else you'll lose your markup:

var crumb = $('.woocommerce-breadcrumb').html();

Then apply the value back to the element:

$('.woocommerce-breadcrumb').html(crumb.replace("Product", brandname));

Alternatively, a much easier way would be to put "Product" in its own element, and then just replace that element's text:

<nav class="woocommerce-breadcrumb"><a href="http://domain.com/" class="home">Home</a> &gt; <span class="item">Product</span></nav>

Then your jQuery would simply be:

$(".woocommerce-breadcrumb .item").text(brandname);

Upvotes: 3

sp00m
sp00m

Reputation: 48837

.replace returns a new string, so you have to set the text of crumb with the returned string.

Upvotes: 0

Related Questions