Javascript - check if string is part of a string in an array - javascript

I have an array which lists a couple of websites:
var validSites = new Array();
validSites[0] = "example_1.com";
validSites[1] = "example_2.com";
validSites[2] = "example_3.com";
now i have a small script which checks what web address you are on and could return something like this:
example_1.com/something/something_else
now i need to check if that address is one of the valid sites.
so
example_1.com/*ANYTHING*
would pass as correct.
but
exampleshmample.com
would pass as incorrect.
Now i know you can do an indexOf() which can check if a string is part of a string and it would return -1 if false. but how would i check it through the entire array?
P.s - its for a Chrome Extension.
thanks

Here’s an idea:
var str = 'example_1.com/something/something_else';
if( validSites.indexOf( str.split('/')[0] ) > -1 ) {
// is valid
}
Another one is to use regexp on a joined array:
var str = 'example_1.com/something/something_else';
new RegExp('^('+validSites.join('|')+')','i').test(str);
This will also match f.ex example_1.comyoyoyo

if (validStates.indexOf("example_1.com") > -1) {
// Then it's inside your array
}
else {
// Then it's not inside your array
}

I'd go with json notation, if you can switch from an array, in this scenario
var validSites = {
"example_1.com":"valid",
"example_2.com":true,
"example_3.com":1 //you could even start putting paths in here to beef up your check.
};
//..your check function would be:
.....
if(validSites[window.location.hostname]){
return true;
}else{
return false;
}

You can achieve this by looping and setting flag variable, Try this, i am not tested this.
Just i typed the code directly. i think this may help you
var flag =0;
var givenurl='example_1.com/*ANYTHING*';
for(int i=0 i<validSites.length;i++){
if(givenurl.indexOf(validSites[i])){
flag=1 //Found
}
}
if(flag) { //Url Found }else{ //not found }

Related

How to find whole substring in string?

I have a string and I have to check if that string contains defined substring I need to do some work and otherwise, I should return some error.
I have the following code:
function isContains(myString) {
let subString = 'test1234';
if(myString.includes(subString)) {
// to do some work
} else {
// return some error.
}
}
but the problem is if myString = 'my-string-test1-rrr' its condition return true.
How can I get true only in case when the whole subString was included in myString?
Use indexOf() instead.
function isContains(myString) {
let subString = 'test1234';
if(myString.indexOf(subString) > -1) {
// to do some work
} else {
// return some error.
}
}
you can use regex to check if that value is present are not;
example 1
without containing the specific string
var test = 'my-string-test1-rrr';
console.log(' test --- ', test.match(/test1234/g))
example 2
contains the specific string
var test = 'my-string-test1234-rrr';
console.log(' test --- ', test.match(/test1234/g))
It is highly recommended to use includes() over indexOf() and further indexOf returns the index of the occurrence where you would prefer an immediate answer - false / true if that substring is found inside the searched string.
Your function does exactly what you are asking. I would suggest to isolate the retrieval of this function and make it purer like so, then when you have the return boolean value you could utilize it after to run whatever logic you wish. This way you keep this function pure and separate your concerns better.
I also believe it would be easier for you to debug your issue if you isolate this functions like In the example I provided.
function isContains(myString) {
let subString = 'test1234';
let isContains = false;
if(myString.includes(subString)) {
isContains = true;
} else {
isContains = false;
}
return isContains;
}
You could use it like so in a later phase in your code:
const myString = 'my-string-test1-rrr';
let shouldRunOtherLogic = isContains(myString);
if (shouldRunOtherLogic) {
// to do some work
} else {
// return some error.
}
Hope I could help, if there's anything further you may need feel free to let me know.

Using Javascript Array Filter method to apply logic [duplicate]

I have search through quite a lot of questions here, but havent found one that i think fits my bill, so if you know of one please link to it.
I have an array that i want to search through for a specific number and if that number is in the array, i then want to take an action and if not then another action.
I have something like this
var Array = ["1","8","17","14","11","20","2","6"];
for(x=0;x<=Array.length;x++)
{
if(Array[x]==8)
then change picture.src to srcpicture1
else
then change picture.src to srcpicture2
}
but this will run the lenght of the array and end up checking the last element of the array and since the last element is not 8 then it will change the picture to picture2.
Now i can see why this happens, i just dont have any ideas as to how to go about checking if an array contains a specific number.
Thanks in advance.
What you can do is write yourself a function to check if an element belongs to an array:
function inArray(array, value) {
for (var i = 0; i < array.length; i++) {
if (array[i] == value) return true;
}
return false;
}
And the just do:
var arr = ["1","8","17","14","11","20","2","6"];
if (inArray(arr, 8)) {
// change picture.src to srcpicture1
} else {
// change picture.src to srcpicture2
}
It's a lot more readable to me.
For extra points you can add the function to the array prototype like so:
Array.prototype.has = function (value) {
for (var i = 0; i < this.length; i++) {
if (this[i] === value) return true;
}
return false;
};
And then the call would be
if (arr.has(8)) // ...
Pushing this even further, you can check for indexOf() method on array and use it - if not - replace it with the code above.
P.S. Try not to use Array for a variable name, since it's reserved for the actual array type.
use this
http://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Objects/Array/IndexOf
ie version
https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Objects/Array/IndexOf#Compatibility
Why don't just you abort the loop when you find the right number :
for(x=0;x<=Array.length;x++)
{
if(Array[x]==8) {
//change picture.src to srcpicture1
break;
}
}
You could sort the array first then check the array only up to the point at which a number would be in the array, were it to exist.
If you have unique keys and a faster retrieval is what you care about a lot, you can consider using a map instead of an array (if there's a hard-bound case of using an array, then it won't work of course). If using a map, you just check "if( num in arr ) ".

How to find the missing next character in the array?

I have an array of characters like this:
['a','b','c','d','f']
['O','Q','R','S']
If we see that, there is one letter is missing from each of the arrays. First one has e missing and the second one has P missing. Care to be taken for the case of the character as well. So, if I have a huge Object which has all the letters in order, and check them for the next ones, and compare?
I am totally confused on what approach to follow! This is what I have got till now:
var chars = ("abcdefghijklmnopqrstuvwxyz"+"abcdefghijklmnopqrstuvwxyz".toUpperCase()).split("");
So this gives me with:
["a","b","c","d","e","f","g","h","i","j","k","l","m",
"n","o","p","q","r","s","t","u","v","w","x","y","z",
"A","B","C","D","E","F","G","H","I","J","K","L","M",
"N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
Which is awesome. Now my question is, how do I like check for the missing character in the range? Some kind of forward lookup?
I tried something like this:
Find the indexOf starting value in the source array.
Compare it with each of them.
If the comparison failed, return the one from the original array?
I think that a much better way is to check for each element in your array if the next element is the next char:
function checkMissingChar(ar) {
for (var i = 1; i < ar.length; i++) {
if (ar[i].charCodeAt(0) == ar[i-1].charCodeAt(0)+1) {
// console.log('all good');
} else {
return String.fromCharCode(ar[i-1].charCodeAt(0)+1);
}
}
return true;
}
var a = ['a','b','c','d','f']
var b = ['O','Q','R','S']
console.log(checkMissingChar(a));
console.log(checkMissingChar(b));
Not that I start to check the array with the second item because I compare it to the item before (the first in the Array).
Forward Look-Ahead or Negative Look-Ahead: Well, my solution would be some kind of that. So, if you see this, what I would do is, I'll keep track of them using the Character's Code using charCodeAt, instead of the array.
function findMissingLetter(array) {
var ords = array.map(function (v) {
return v.charCodeAt(0);
});
var prevOrd = "p";
for (var i = 0; i < ords.length; i++) {
if (prevOrd == "p") {
prevOrd = ords[i];
continue;
}
if (prevOrd + 1 != ords[i]) {
return String.fromCharCode(ords[i] - 1);
}
prevOrd = ords[i];
}
}
console.log(findMissingLetter(['a','b','c','d','f']));
console.log(findMissingLetter(['O','Q','R','S']));
Since I come from a PHP background, I use some PHP related terms like ordinal, etc. In PHP, you can get the charCode using the ord().
As Dekel's answer is better than mine, I'll try to propose somewhat more better answer:
function findMissingLetter (ar) {
for (var i = 1; i < ar.length; i++) {
if (ar[i].charCodeAt(0) != ar[i-1].charCodeAt(0)+1) {
return String.fromCharCode(ar[i-1].charCodeAt(0)+1);
}
}
return true;
}
var a = ['a','b','c','d','f']
var b = ['O','Q','R','S']
console.log(findMissingLetter(a));
console.log(findMissingLetter(b));
Shorter and Sweet.

How to find if a value matches one of the values from an array in Javascript [duplicate]

This question already has answers here:
How do I check if an array includes a value in JavaScript?
(60 answers)
Closed 6 years ago.
FYI: this is for a simple quiz with just a single input field for each answer.
I have the following Javascript if statement to check if the value entered into an input field is correct (in this case, if the value entered is 'england').
$('input').keyup(function () {
if ($(this).val().toLowerCase() == 'england') {
//Stuff
} else {
//Other Stuff
};
});
However, I want to allow for alternative spellings, so I need a few possible answers for each question - it seems sensible to use an array for this as so...
var ans1 = new Array();
ans1[0] = "England";
ans1[1] = "Englund";
ans1[2] = "Ingland";
How can I change my if statement to say 'if the input field value equals any of those values from the array, then do the following'?
Any help would be greatly appreciated! Thank you.
You can do this using .inArray():
if ($.inArray($(this).val(), ans1) > -1) {
//Stuff
}
Here, the code $.inArray($(this).val(), ans1) will search for a specified value for example England within an array ans1 and return its index (or -1 if not found).
UPDATE
For case-sensitive search:
First enter all the values in the array in Lower Case
Next use the code below:-
JS:
if ($.inArray($(this).val().toLowerCase(), ans1) > -1) {
//Stuff
}
You can use the 'indexOf' method of the array, this will return -1 if the value doesn't exist in the array:
//if answer is in array
if(array.indexOf(answer) != -1){
//do stuff
}else{
//do stuff
}
Try this
if(this.value.match(/^(England|Englund|Ingland)$/i))
using regex and gi modifier for case insensitive
Do like this
$('input').keyup(function () {
var ans1 = new Array();
ans1[0] = "England";
ans1[1] = "Englund";
ans1[2] = "Ingland";
for(int i=0;i<ans1.length;i++)
{
if ($(this).val().toLowerCase() ==ans1[i]) {
//Stuff
} else {
//Other Stuff
};
}
});
Perhaps you may consider checking each element of the array like that:
var ans1 = new Array();
ans1[0] = "England";
ans1[1] = "Englund";
ans1[2] = "Ingland";
$('input').keyup(function () {
for (var i = 0; i < ans1.length; i++) {
if ($(this).val().toLowerCase() == ans1[i]) {
//Stuff
} else {
//Other Stuff
};
}
});
Not the most beautiful solution, but it should work.
jQuery offers $.inArray:
var found = $.inArray('specialword', words) > -1;
Note that inArray returns the index of the element found, so 0 indicates the element is the first in the array. -1 indicates the element was not found.
put your spellings in an array like this:
words: [
"England"
"Inglund"
"Ingland"
]
Found will be true if the word was found.
If you want the index of the matched word delete > -1 from the line.
Your code would be like this:
$('input').keyup(function () {
var found = $.inArray($(this).val(), words);
found > -1 ? //Stuff : //otherStuff;
});

Use Javascript or jQuery to create an array from an array

Assume you have an array:
var arrStateCityAll=['CA_Alameda','CA__Pasadena','CA_Sacramento','NY_Albany','NY_Buffalo','NY_Ithaca']
Is there an easy way using javascript and/or jQuery to filter the arrStateCityAll to get a new array (a subset of arrStateCityAll); something like this:
// return's ['CA_Alameda','CA__Pasadena','CA_Sacramento']
var arrStateCityCA=FilterArray('CA',arrStateCityAll);
Likely you want to do a regex on each item. You can do this with jQuery's grep function.
http://api.jquery.com/jQuery.grep/
You can use javascript's Array.filter.
var arrStateCityAll = ['CA_Alameda','CA__Pasadena','CA_Sacramento','NY_Albany','NY_Buffalo','NY_Ithaca']
var arrStateCityCA = arrStateCityAll.filter( function (element) {
return element.indexOf("CA_") == 0;
});
The mozilla documentation linked to above has a solution for browsers that don't implicitly support filter.
This should work.
var arrStateCityCA = [];
for (var i = 0;i<arrStateCityAll.length;i++){
if (arrStateCityAll[i].substr(0,2) == 'CA'){
arrStateCityCA.push(arrStateCityAll[i]);
}
}
You could use jQuery.grep
var arrStateCityCA =
$.grep(arrStateCityAll,function(el,i){return (el.substring(0,2)=='CA')});
Demo at jsfiddle
To implement you actual FilterArray function as shown in your post you could do
function FilterArray(state,arr){
return $.grep(arr,
function(el,i) {return (el.substring(0,2)==state)}
);
}
This makes a few assumptions.
State is always 2 chars.
State is always the first 2 chars.
And of course remember case-sensitivity (this function is case sensitive) ie 'CA' not equal to 'Ca'.
if you are going to have an undescore between your state and city name, you can split on the underscore and test against the first array value
function getSubSetByState(set,state) {
var result = [];
for(var i=0,l=set.length;i<l;++i) {
if(set[i].split('_')[0] === state) {
result.push(set[i]);
}
}
return result;
}
Use if by giving it the set of places, and then the state you are searching for.

Categories

Resources