简体   繁体   中英

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

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, ie your <a> tag.

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);

.replace返回一个新字符串,因此必须使用返回的字符串设置crumb文本。

其替换为演示。

var brandname = 'My Name';

var crumb = 'My Product';

console.log(crumb);

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

alert(d);

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

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');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM