Reputation: 623
Hi I have a problem where I am getting text from a div class and inserting it into a h1 using:
var newHeadingText = $(".list-group-item.active").text();
$("#content-wrap").prepend("<h1 class=\"newHeading\">" + newHeadingText + "</h1>");
The text called contains a number (various depending on number in cart) and a specific text string. "Premium Tablets 3Items in cart".
I want to remove the #Items in cart.
I can remove the text:
$(".newHeading:contains('Items in cart')").html(function(_, html) {
return html.replace(/Items in cart/g, '');
});
But because sometimes there is a number in the 'Premium Tablets' like 'Premium Tablets 12". I only want to remove the number that appears directly before the 'Items in cart'.
How do I remove only the text and the preceding number?
Thank you
Upvotes: 0
Views: 51
Reputation: 19772
EDIT - I originaly missunderstood the requirements, as the question states "remove preceding number". This replaces/removes x items in cart
$(".newHeading:contains('Items in cart')").html(function(_, html) {
return html.replace(/(\d+ items in cart)/gi, '');
});
See: https://regex101.com/r/Nhh9Bf/1
Original
You can use "positive look ahead". This removes the number immediately preceding Items in cart
$(".newHeading:contains('Items in cart')").html(function(_, html) {
return html.replace(/(\d+ )(?=items in cart)/gi, '');
});
See: https://regex101.com/r/irn5Sq/1/
Alternatively, consider wrapping x items in cart
in a span with a class. This gives you two benefits, you can now style that segment as required to make it stand out a little more and you now have a hook you can use to modify the string easier. You could even extend this to wrapping the number explicitly.
Upvotes: 3
Reputation: 623
I found a simple solution.
$(".newHeading:contains('Items in cart')").html(function(_, html) {
return html.replace(/[0-9]Items in cart/g, '');
});
Upvotes: 0
Reputation: 814
This type of approach splits the elements down to 2 sides, where one is the Items in Cart and one for the number. If your number is always attached to the left of Items in Cart, this should always get the number (No matter the length) and take it out.
function remove_string() {
var str = "Jelly Ranchers 12 Items in Cart";
var string_split = str.split("Items in Cart");
var sub_split = string_split[0].split(" ");
var number_split = sub_split[sub_split.length - 2];
var right_string = str.replace("Items in Cart","");
var final_str = right_string.replace(number_split,"");
console.log(final_str);
}
<h2>Click the button below</h2>
<p>Original String: "Jelly Ranchers 12 Items in Cart"</p>
<p>I want to remove 12 Items in Cart from this text</p>
<button onclick="remove_string()">Try it</button>
Upvotes: 0