In JavaScript, How to Search an Array for a Substring Match

In javascript, how do you search an array for a substring match

In your specific case, you can do it just with a boring old counter:

var index, value, result;
for (index = 0; index < windowArray.length; ++index) {
value = windowArray[index];
if (value.substring(0, 3) === "id-") {
// You've found it, the full text is in `value`.
// So you might grab it and break the loop, although
// really what you do having found it depends on
// what you need.
result = value;
break;
}
}

// Use `result` here, it will be `undefined` if not found

But if your array is sparse, you can do it more efficiently with a properly-designed for..in loop:

var key, value, result;
for (key in windowArray) {
if (windowArray.hasOwnProperty(key) && !isNaN(parseInt(key, 10))) {
value = windowArray[key];
if (value.substring(0, 3) === "id-") {
// You've found it, the full text is in `value`.
// So you might grab it and break the loop, although
// really what you do having found it depends on
// what you need.
result = value;
break;
}
}
}

// Use `result` here, it will be `undefined` if not found

Beware naive for..in loops that don't have the hasOwnProperty and !isNaN(parseInt(key, 10)) checks; here's why.


Off-topic:

Another way to write

var windowArray = new Array ("item","thing","id-3-text","class");

is

var windowArray = ["item","thing","id-3-text","class"];

...which is less typing for you, and perhaps (this bit is subjective) a bit more easily read. The two statements have exactly the same result: A new array with those contents.

How to check if a string contains text from an array of substrings in JavaScript?

There's nothing built-in that will do that for you, you'll have to write a function for it, although it can be just a callback to the some array method.

Two approaches for you:

  • Array some method
  • Regular expression

Array some

The array some method (added in ES5) makes this quite straightforward:

if (substrings.some(function(v) { return str.indexOf(v) >= 0; })) {
// There's at least one
}

Even better with an arrow function and the newish includes method (both ES2015+):

if (substrings.some(v => str.includes(v))) {
// There's at least one
}

Live Example:

const substrings = ["one", "two", "three"];
let str;

// Setup
console.log(`Substrings: ${substrings}`);

// Try it where we expect a match
str = "this has one";
if (substrings.some(v => str.includes(v))) {
console.log(`Match using "${str}"`);
} else {
console.log(`No match using "${str}"`);
}

// Try it where we DON'T expect a match
str = "this doesn't have any";
if (substrings.some(v => str.includes(v))) {
console.log(`Match using "${str}"`);
} else {
console.log(`No match using "${str}"`);
}

Check if an array of strings contains a substring

Because includes will compare '#' with each array element.

Let's try with some or find if you want to find if you want to get exactly element

var array = ["123", "456", "#123"];
var el = array.find(a =>a.includes("#"));
console.log(el)

Javascript match two arrays with substring search

Here is how you can simple get this done

var ArrayFileName = ['one', 'two', 'three', 'three', 'five', 'six', 'ten'];
var ArrayFileNameWExt = ['one.txt', 'two.txt', 'three.txt', 'ten.wmf', 'eleven.cgm'];
var FinalArray = [];

for (var i = 0; i < ArrayFileName.length; i++) {
for (var j = 0; j < ArrayFileNameWExt.length; j++) {
var temp = ArrayFileNameWExt[j].split(".");
if(ArrayFileName[i]==temp[0]){
FinalArray.push(ArrayFileNameWExt[j]);
break;
}
}
}

How can one check if an array contains a substring?

The Array.prototype has very useful .filter function for your purpose.

const arr = ['positive', 'positron', 'negative', 'negatron'];
function findMatches() { let searchVal = document.getElementById('test').value; let res = arr.filter(el => el.indexOf(searchVal) > -1); document.getElementById('result').innerHTML = res.join(', ');}
<input type="text" id="test" /><button type="button" onclick="findMatches()">Find</button><br /> Array: ['positive', 'positron', 'negative', 'negatron']<br /><span id="result"></span>

How can I find match string in array javascript?

This should work:

var str = "https://exmaple.com/u/xxxx?xx=x";var filters = ["/u","/p"];
for (const filter of filters) { if (str.includes(filter)) { console.log('matching filter:', filter); break; // return 1; if needed }}

find object in array, to find object where id match substring

Use String#match.

console.log(res.data.features.find(place => place.id.match(region)))

const arr = [{id: "address.7576869587107444", type: "Feature"},
{id: "postcode.12959148828066430", type: "Feature"},
{id: "place.14392640799224870", type: "Feature"},
{id: "region.9375820343691660", type: "Feature"},
{id: "country.13200156005766020", type: "Feature"}];
let region = /region/gi;
console.log(arr.find(place => place.id.match(region)))

Check if a substring exists in an array Javascript

The includes array method checks whether the string "Gold" is contained as an item in the array, not whether one of the array items contains the substring. You'd want to use some with the includes string method for that:

Ressources.some(res => res.includes("Gold"))


Related Topics



Leave a reply



Submit