Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove a character from the middle of a string: without removing inner element

This one has me stumped. I want to remove the "+" from a label element. Here's the HTML:

 <label class="option" for="edit-attributes-21-33">
 <input type="radio" id="edit-attributes-21-33" name="attributes[21]" 
 value="33" checked="checked" class="form-radio"> 4 oz, +$15.00</label>

I started with this

$(".option").each(function(index, value) {

$(this).text( $(this).text().replace("+", ""));

})

This removes the "+" but also strips out the input element. So then I tried:

$(".option").each(function(index, value) {

var oldString = $(this).html();
var newString = oldString.replace("+", "");
console.log(oldString, newString);
$(this).text(newString);

})

This makes a string of the correct html mark-up, but it's a string and is passed back to the DOM that way. I've seen another post with the same problem, but no solution.

like image 241
icicleking Avatar asked Apr 15 '15 19:04

icicleking


1 Answers

You can achieve what you want using your code by using .html() instead of .text():

$(".option").each(function(index, value) {
    var oldString = $(this).html();
    var newString = oldString.replace("+", "");
    console.log(oldString, newString);
    $(this).html(newString);
});

Here's the JQuery .html() method ref: https://api.jquery.com/html/

Here's the Fiddle: https://jsfiddle.net/Darkseal/1c572Luw/

I also slightly modified your <input> end tag to make it XHTML compliant.

like image 120
Darkseal Avatar answered Oct 16 '22 07:10

Darkseal