'lodash _.contains one of multiple values in string
Is there a way in lodash to check if a strings contains one of the values from an array?
For example:
var text = 'this is some sample text';
var values = ['sample', 'anything'];
_.contains(text, values); // should be true
var values = ['nope', 'no'];
_.contains(text, values); // should be false
Solution 1:[1]
Use _.some and _.includes:
var text = 'this is some sample text';
var values = ['sample', 'anything'];
console.log(_.some(values, (el) => _.includes(text, el)));
var values = ['no', 'nope'];
console.log(_.some(values, (el) => _.includes(text, el)));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>
The more modern approach would be to use native JS to achieve the same thing without the need for an external library.
const text = 'this is some sample text';
const values1 = ['sample', 'anything'];
const values2 = ['no', 'nope'];
function test(text, arr) {
return arr.some(el => {
return text.includes(el);
});
}
console.log(test(text, values1));
console.log(test(text, values2));
Solution 2:[2]
No. But this is easy to implement using String.includes. You don't need lodash.
Here is a simple function that does just this:
function multiIncludes(text, values){
return values.some(function(val){
return text.includes(val);
});
}
document.write(multiIncludes('this is some sample text',
['sample', 'anything']));
document.write('<br />');
document.write(multiIncludes('this is some sample text',
['nope', 'anything']));
Solution 3:[3]
Try this:
-JS
var cnt = 1;
$(".slider").each(function () {
$(this).attr('id', function (index) {
return "sld-" + cnt;
});
cnt++;
});
$('.slider').each(function(key, item){
var id = $(this).attr("id");
var sliderId = '#' + id;
if ($(sliderId).length) {
var currentSlide;
var slidesCount;
var sliderCounter = document.createElement('div');
sliderCounter.classList.add('slider-counter');
var updateSliderCounter = function(slick, currentIndex) {
currentSlide = slick.slickCurrentSlide() + 1;
slidesCount = slick.slideCount;
$(sliderCounter).text(currentSlide + '/' +slidesCount)
};
$(sliderId).on('init', function(event, slick) {
$(sliderId).append(sliderCounter);
updateSliderCounter(slick);
});
$(sliderId).on('afterChange', function(event, slick, currentSlide) {
updateSliderCounter(slick, currentSlide);
});
$(sliderId).slick({
slidesToShow: 1,
dots: false,
adaptiveHeight: true,
});
}
});
-html
<div class="slider">
<img>
<img>
<img>
</div>
-CSS
.slider-counter {
position: absolute;
font-size: 20px;
letter-spacing: 2px;
font-weight: 400;
top: 5px;
left: 45px;
z-index: 11;
pointer-events: none;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | |
| Solution 3 |
