Reputation: 75
Trying to convert a small snippet from jQuery to JS, I'm getting an array that contains strings instead of an array with numbers.
To be more exact, I'm getting this with script rewritten in JS:
The converted JS code looks like:
let pickEl = document.querySelectorAll('.someClass');
// console.log(pickEl);
pickEl.forEach(pickEl => {
let r = new RegExp('(' + term + ')', "ig");
if(pickEl.textContent.match(r)) {
// console.log(pickEl.innerHTML.match(r));
let matches = pickEl.textContent.match(r);
matches.forEach(function(i) {
occurrences.push(i);
});
// wrap each found term in span with class found to highlight it
pickEl.innerHTML.replace(r, '<span class="found">$&</span>');
console.log(pickEl.textContent.replace(r, '<span class="found">$&</span>'));
}
});
Instead of this in jQuery:
The jQuery code looks like:
$('.some').each(function (i) {
var r = new RegExp('(' + term + ')', "ig");
if ($(this).html().match(r)) {
var matches = $(this).html().match(r);
console.log(matches);
console.log('Var matches =' + ' ' + matches);
$.each(matches, function () {
occurences.push(i);
});
// wrap each found search term with our `found` span to highlight it
$(this).html($(this).html().replace(r, '<span class="found">$1</span>'));
}
});
How should I write the JS code in order to obtain the same array as in jQuery?
Upvotes: 0
Views: 75
Reputation: 66103
That is because of what i
actually is in your two codes: in the native JS version, i
refers to the entries returned by String.prototype.match
, while i
in your jQuery version comes from the first argument of the .each
method, which is the index.
If you want to access the index, then you need to get it from the outer forEach function applied to pickEl
. Refer to the comments with // NOTE:
, where I have added my annotations:
let pickEl = document.querySelectorAll('.someClass');
// NOTE: Access the index of the current element
pickEl.forEach((pickEl, index) => {
let r = new RegExp('(' + term + ')', "ig");
if(pickEl.textContent.match(r)) {
// console.log(pickEl.innerHTML.match(r));
let matches = pickEl.textContent.match(r);
matches.forEach(function() {
// NOTE: Push the index into array
occurrences.push(index);
});
// wrap each found term in span with class found to highlight it
pickEl.innerHTML.replace(r, '<span class="found">$&</span>');
console.log(pickEl.textContent.replace(r, '<span class="found">$&</span>'));
}
});
Upvotes: 1