简体   繁体   中英

Replacing Text with RegEx and jQuery

I have code that looks like so:

<li class="capture-details">
  Special Instructions
   <br>
<textarea id="catProdInstructions_6795606" class="productTextarea"></textarea>
</li>

Everything inside the li tag is generated by my CMS and I would like to remove the words Special Instructions but leave the code after this alone.

I tried this:

var text = $('.capture-details').text().replace(/Special Instructions/, 'Your Personalized Message');
$('.capture-details').text(text);

but this removed the textarea as well. I then tried:

$('.capture-details').prepend(text);

but that didn't remove the words Special Instructions .

How would I remove the words Special Instructions ?

Here is a fiddle of the above code.

Note: I could hard code the textarea into my JS but I want to avoid this because the textarea id and class may change but not the words Special Instructions .

You could just get the textNode and set it's value

$('.capture-details')[0].firstChild.nodeValue = 'Your Personalized Message'

FIDDLE

$(function() {
    var el = $('.capture-details');
    el.html(el.html().replace(/Special Instructions/, 'Your Personalized Message'));
});

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