I have some DIVs with text, like so:
<div class="testclass"><b><i>1 Banana<i></b></div>
<div class="testclass"><b><i>2 Oranges<i></b></div>
<div class="testclass"><b><i>2 Peaches<i></b></div>
<div class="testclass"><b><i>1 Watermelons<i></b></div>
<div class="testclass"><b><i>1 Dragon Fruit<i></b></div>
I'm attempting to grab the text in each testclass and create a list, like so:
Banana
Oranges
Oranges
Peaches
Peaches
Watermelons
What I'm struggling with is replacing the numbers with either nothing, or inserting a new entry into the list with a duplicate.
What I have so far is below:
var fruits = $('.testclass').text();
fruits.replace(/1 /,"") ;
This gives me a list like the following:
Banana
2 Oranges
2 Peaches
1 Watermelons
I'm fairly new to jQuery, so I have no clue how to properly iterate through the list or how to properly duplicate entries with 2 in front of them.
Try this:
var fruits = [];
$('.testclass').each(function(i, el) {
var values = $(this).text().split(' ');
for (var i = 0; i < values[0]; i++) {
fruits.push(values[1]);
}
});
Output:
["Banana", "Oranges", "Oranges", "Peaches", "Peaches", "Watermelons"]
To cater for fruits with spaces in the name, for example Dragon fruit
, try this:
var fruits = [];
$('.testclass').each(function(i, el) {
var values = $(this).text().split(' ');
var count = parseInt(values.shift(), 10);
for (var i = 0; i < count; i++) {
fruits.push(values.join(' '));
}
});
You can use a regular expression:
.replace(/[0-9]/g,'').trim()
/[0-9]/g
will replace all numbers with an empty string. Then here I've used .trim()
to remove trailing whitespace. You'll also need to iterate through each .testclass
using .each()
:
$('.testclass').each(function() {
$(this).text(function() {
return $(this).text().replace(/[0-9]/g,'').trim()
})
});
试试这个正则表达式:
testclass.replace(/[0-9 ]+/,"");
You can use:
$('.testclass').each(function() {
$(this).text(function() {
return $.trim($(this).text().replace(/\d/g,''))
})
});
Try this,
some_fruits = []
$('.testclass').each(function(){
var regex = /\d+/;
if ($(this).text().match(regex)) {
str = $(this).text().replace(regex, " ");
some_fruits.push(str)
}
});
I am used split ()
$(".testclass").each(function(){
var txt=$(this).text();
alert(txt.split(' ')[1])
})
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.