Javascript Get Multiple Substrings Within One String - javascript

how to get multiple occurences of words in a string. I've tried multiple functions but with no success. I know I can get back the first true value using some() method as below.
var keyword_array = ["Trap","Samples","WAV","MIDI","Loops"];
function validateContentKeywords(content,keyword){
keyword.some(function(currentValue,index){
console.log(currentValue + " ");
return content.indexOf(currentValue) >= 0;
});
}
// Outputs --> Trap Samples
if(validateContentKeywords("Beat Loops WAV Trap Samples Dog Cat MIDI",keyword_array)){
console.log("Matches");
}
// What I Want is --> Trap,Samples,MIDI,Loops
The above function only outputs 2 occurences and I want it to output all of the matching values at the same time such as --> Trap,Samples,MIDI,Loops.
Is there a way to get multiple occurences of words in a string at the same time?
UPDATED:: The solution that helped me out is below
function Matches(value){
return "Beat Loops WAV Trap Samples Dog Cat MIDI".indexOf(value) !== -1;
}
var keyword_array = ["Trap","Samples","WAV","MIDI","Loops"].filter(Matches);
document.write(keyword_array);

You seem to be looking for the filter Array method that returns an array of the matched elements, instead of an boolean value whether some matched.

var keyword_array = ["Trap", "Samples", "WAV", "MIDI", "Loops"];
function validateContentKeywords(content, keyword) {
var words = content.split(' '); //split the given string
for (var i = 0; i < words.length; i++) {
if (keyword.indexOf(words[i]) > -1) { //check if actually iterated word from string is in the provided keyword array
document.write(words[i] + " "); //if it is, write it to the document
};
}
}
validateContentKeywords("Beat Loops WAV Trap Samples Dog Cat MIDI", keyword_array);

The easiest way to do it would be this:
keyword_array.filter(keyword => searchString.includes(keyword));
You can learn more about filter here. I highly recommend learning about how to use map, reduce and filter. They are your best friends.

Related

When I turn document.cookie into an array, and then use conditional statement with indexof, it works only for the first value. Why?

It's hard to even describe the question. I can't reproduce a snippet, obviously because it requires using cookies, but I will try to reproduce it with a normal array, and show you how it should work, then I'll show you screenshots of my code, and the outcome it produces when used on real cookies.
function cookiename(name) {
//var test5 = document.cookie.split(";");
var test5 = ["user=Jim Jordan", "color=blue", "cat=bella", "username=NikoaTesla"];
var username2 = name;
var output = "";
if(test5[0].indexOf("user") == 0) {
output = test5[0].substring(username2.length, test5[0].length);
} else alert("IT DOES NOT WORK");
alert(output);
}
cookiename("user");
This is pretty much what my code looks like, except that, instead of array, test5 is assigned to document.cookie.split(";"), and it contains two more cookies.
Now, the way it works is, you create a conditional statement with the array value, in this case, test5[0], which contains the value "user=Jim Jordan", and say, if the indexof("user") string is in position 0 inside the test5[0] string, which contains the value user=Jim Jordan, then execute the condition, if not, alert that it doesn't work.
Now, as you saw, it works great in the above example. It works as expected with any of the other array values. test5[1], test5[2] etc. will work the same way, of course in the above example they won't match the condition, but if you change the indexof string, it works.
Now, the issue I have is that, the test5 variable stores the document.cookie.split(";") array, and only the first array value works, while the others don't, even though the condition should be matching. However, the other values do work but only if the indexof string is intentionally wrong, and doesn't exist inside the array value, and the condition is of course -1. If the indexof string actually exists, both 0 and -1 conditions don't match. Very strange.
Here's a screenshot of my code, and subsequent result:
First array value
So, as you can see, the first value works as expected.
But then, when I try with another array value, it doesn't work. The third array value is called username=Sam Jones. This is what happens when I change indexof("user") with indexof("username").
Third array value
As you can see, the prior alert that I inserted displays that test5[2] contains the value of username=Sam Jones, but then when use it as a condition, the indexof("username") does not match it. It should be 0, but it's not. Even when I try -1, instead of 0, which matches strings that do not exist, it still produces the exact same outcome! Why!?
Now, watch what happens when I add a string in indexof that does not exist. Instead of the string username, I will add something random, and use -1 as a condition.
Different indexof string on Third array value
As you see, now the random indexof string matches the -1, because it doesn't exist. But why when the indexof string actually does exist, neither 0 nor -1 match the condition?
Why only the first array value work?
Does anyone have any idea what is happening here?
Your approach is flawed since you are expecting that the cookie will always be in the same order. You are also checking for the start of a string equals. When you have user, it will also match username. You are not accounting for the = and you are not removing the encoding.
So to do it with your approach with indexOf and substring, you would need to loop over and check that it has a match
function getCookie(key) {
// var myCookies = document.cookie.split(/;\s?/g);
var myCookies = ["user=Jim%20Jordan", "color=blue", "cat=bella", "username=NikoaTesla"];
for (var i = 0; i < myCookies.length; i++) {
var current = myCookies[i];
if (current.indexOf(key + "=") === 0) {
return decodeURIComponent(current.substr(key.length+1));
}
}
}
console.log('user', getCookie('user'));
console.log('username', getCookie('username'));
console.log('funky', getCookie('funky'));
Most approaches would use a regular expression.
function getCookie(key) {
// var myCookies = document.cookie;
var myCookies = "user=Jim%20Jordan;color=blue;cat=bella;username=NikoaTesla";
var cookieValue = myCookies.match(`(?:(?:^|.*; *)${key} *= *([^;]*).*$)|^.*$`)[1]
return cookieValue ? decodeURIComponent(cookieValue) : null;
}
console.log('user', getCookie('user'));
console.log('username', getCookie('username'));
console.log('funky', getCookie('funky'));
If I have to read multiple values I would map it to an object
function getCookieValues() {
// var myCookies = document.cookie.split(/;\s?/g);
var myCookies = ["user=Jim%20Jordan", "color=blue", "cat=bella", "username=NikoaTesla"];
return myCookies.reduce(function (obj, item) {
var parts = item.split("=");
obj[parts[0]] = decodeURIComponent(parts[1]);
return obj;
}, {});
}
var myCookies = getCookieValues();
console.log('user', myCookies['user']);
console.log('username', myCookies['username']);
console.log('funky', myCookies['funky']);
What you want is to find cookies starting with name, correct?
Firstly, you are probably aware, but it is good to note that if your cookies come this way: cookies = "user=Jim Jordan; color=blue; cat=bella; username=NikoaTesla";, you have to split for "; " instead of just ";".
Once your splits are correct, already without any leading spaces, you only need:
test5.filter(c=>c.trim().startsWith("user"));
I believe startsWith is cleaner than using indexOf.
Another solution, without split:
For the "; " case:
const cookiestr='; '+cookies+';';
while (true) { i=cookiestr.indexOf('; user',i+1); if (i<0) break; console.log(cookiestr.substring(i+2,cookiestr.indexOf(';',i+1))); }
For the ";" case:
const cookiestr=';'+cookies+';';
while (true) { i=cookiestr.indexOf(';user',i+1); if (i<0) break; console.log(cookiestr.substring(i+1,cookiestr.indexOf(';',i+1))); }
In your conditional, test5[2] = “cat=bella”, not “username=NikolaTesla”. That’s at index 3. Could try that?
Also check for white spaces being being added to the front of end of each string like someone mentioned already.

Removing words from array using regex

I am creating a program that involves removing text from an array. If a letter is included in a word in the array, then that word will be removed. My first test was successful, a simple regular expression with a small array:
var regex = /z/;
var words = ["eggs", "zebras", "lampshade"];
for (i = 0; i < words.length; i++) {
let testResult = regex.test(words[i]);
if (!testResult) {
words.splice(i, 1);
}
}
console.log(words);
As expected, it returned [ 'zebras' ]. Because this was successful, I quickly scaled up using an npm package called "an-array-of-english-words". I ran my new script:
const masterWords = require("an-array-of-english-words");
var regex = /z/;
var words = masterWords;
for (i = 0; i < words.length; i++) {
let testResult = regex.test(words[i]);
if (!testResult) {
words.splice(i, 1);
}
}
console.log(words);
Every time I run it it ends up returning values that do not abide by the regular expression. For example, the code above returned ['aa', 'aahed', 'aahs', ...] as its first few values. Do I have to change my code to deal with a bigger array? Am I making a stupid mistake I didn't notice?
I think it may be due to the fact that you are splicing the array and looping it at the same time.
For ex. if the length of array is 5 and the current index is 2, after splicing the array, the item at the index 3 will be moved to the index 2, and will be skipped in the next iteration, since the next index will be 3.
So, you can create a clone of the words and change it, while iterating the original array.
#Joey , in official documentation if you see , try using it this way as a workaround . Also #Igor Moraru's answer explains why the issue might be happening.
console.log(words.filter(d => /z/.test(d)))

Removing array elements that contain a number

I have seen several answers on Stackoverflow but none have helped me. I have a huge array of nearly 100,000 words, of which I am trying to remove all words that contain a number. I am using the following to do that:
for(var i = 0; i < words.length; i++){
if (hasNumbers(words[i]) {
words.splice(i, 1);
}
function hasNumbers(t)
{ return /\d/.test(t); }
It seems to work, but not all the time because I am still getting words that contain numbers. What can I change to make this remove all words that contain any number at all?
(I am using p5.js with my js)
That is because when you delete a word at index i, the next word will have index i, yet you still increase i, thereby skipping a word which you never inspect.
To solve this you can go backwards through your array:
for(var i = words.length - 1; i >= 0; i--){
// etc.
Here is a shorter way to remove words with digits:
words = words.filter(a => !hasNumbers(a));
Finally, you really should call your second function hasDigits instead of hasNumbers. The words "digit" and "number" have a slightly different meaning.
Here is a snippet, using ES6 syntax, that defines the opposite function hasNoDigits and applies it to some sample data:
let words = ['abcd', 'ab0d', '4444', '-)#', '&9µ*'];
let hasNoDigits = s => /^\D*$/.test(s);
console.log(words.filter(hasNoDigits));
words = words.filter(a => !hasNumbers(a));
I had started writing this and then trincot answered. His answer is correct, though with the popular and widespread usage of ES5 array functions, I feel like you could simplify this down quite a bit.
window.addEventListener('load', function() {
var data = [
'w3.org',
'google.com',
'00011118.com'
]; //This is supposed to be your data, I didn't have it so I made it up.
var no_nums = data.filter(function(item) {
//Tests each string against the regex, inverts the value (false becomes true, true becomes false)
return !/\d/.test(item);
});
var results = document.getElementById('results');
no_nums.forEach(function(item) {
results.innerHTML += item + '<br />';
//Loops through each of our new array to add the item so we can see it.
});
});
<div id="results">
</div>

Removing a value in an object based on if it contains a string

a fairly simple question today.
I have an object that looks like this:
var buttonLogos = {
adcraft: [".","..","1.png","2.png","3.png"],
ferries: [".","..","1.png","2.png"]
}
and I'm looking for a quick way to remove the entries at the beginning with the dots, I would usually just filter out anything with a dot, but I can't because the strings I want contain a .png
it might be a solution to filter out the first two entries, because they will always be "." and ".." but alas I'm not sure how to even do that.
(jQuery is encouraged)
I would love some help! Thanks.
for(i in buttonLogos){
buttonLogos[i] = buttonLogos[i].filter(function(i){
return !i.match(/^\.{1,2}$/);
});
}
You can use js regex as follows,
buttonLogos.adcraft = $(buttonLogos.adcraft).filter(function(i,val){return val.match(/[^\.]/);});
Filters as mentioned in other answers or a combination of indexOf and splice would also work.
var adcraft = [".","..","1.png","2.png","3.png"];
var elems_to_rm = [];
for (var i = 0; i < adcraft.length; i++) {
if (adcraft[i].indexOf('.') === 0) {
elems_to_rm.push(adcraft[i]);
}
}
for (var i = 0; i < elems_to_rm.length; i++) {
var index = adcraft.indexOf(elems_to_rm[i]);
adcraft.splice(index, 1);
}
Try manually. Any number of items can be deleted from the array by specifying just two
arguments: the position of the first item to delete and the number of items to delete. For
example, splice(0, 2) deletes the first two items.

How can I deal with this kind of bug in Javascript? [duplicate]

This question already has answers here:
How could I manipulate this array in Javascript for this kind of error checking?
(4 answers)
Closed 8 years ago.
How can I make sure that two commas are not entered in an Array .. this is for a web application that generates an array from user input and it's a text field .. I cant change it to anything else.
example .. var names=["Kim",,"Andrew","Ashley"];
in this array , we have two consecutive commas, instead of one .. how can i make sure that if the user enters any character that wouldn't be good , I just take it out .. like comma , dot, etc .. for the example of the extra comma , how would this be achieved considering that I have no other option but deal with a text field generating an array like this
Run the array through a function (see below) to remove the invalid values in your array. In your case, the values are undefined for the second element in ["Kim",,"Andrew","Ashley"].
var stripEmpty = function (ary) {
var result = [];
for (var i = 0; i < ary.length; i++) {
if (ary[i] !== undefined) {
result.push(ary[i]);
}
}
return result;
};
Then you can do this:
var names = ["Kim",,"Andrew","Ashley"];
var strippedNames = stripEmpty(names); // ["Kim","Andrew","Ashley"]
See working fiddle: http://jsfiddle.net/amyamy86/LymAZ/
Two consecutive commas (or a leading comma) is an elision, it increments the index of the next member. The elided member doesn't exist as a property of the array. To find such members, you can use the in operator:
var a = [,0,1,, , ,2,3,, ,];
var i = a.length;
while (i--) {
if (!(i in a)) { // returns true if a has no index i
a.splice(i, 1);
}
}
alert(a); // 0,1,2,3
This also deals with extra spaces in the array literal.
This isn't a bug per say, it's just that you are having null entries from your form being added to your array. try this:
//assume your array has been filled up
var mod_names = names.join("#"); // you can use any delimeter apart from '#'
if(mode_names.indexOf(" ") > -1){
mode_names.replace(/\s+/gi, "");
}
mode_names.replace(/#/gi, " ");
mod_names = mod_names.split(); // the default is a space char
names = mode_names;

Categories