I wrote the following code which takes an array and converts it into a filter string, the string gets generated but instead of
product_size=123&product_size=456
I want this to be product_size=123+456.
I suspect I need to check if the array key for product_size already exists and then push the second number into it, then generate the filter string.
I have created a keysAlreadyUsed array but I can't figure out how to do this.
Maybe I am over thinking this and some form of string manipulation would suffice.
// Array
arrayTest = [];
arrayTest.push( ['product_size', 123] );
arrayTest.push( ['product_size', 456] );
arrayTest.push( ['product_color', 123] );
// Start filter string and array of keys already used
filterString = '';
keysAlreadyUsed = [];
// Loop the array test
$.each( arrayTest, function( index1, value1 ) {
// If the key has already been set
if( jQuery.inArray( value1[0], keysAlreadyUsed ) ) {
// Push into the existing array key
} else {
// New array we can loop through later with the product_size and the 123, 456 in it.
}
// Populate filter string
filterString += value1[0] + '=' + value1[1] + '&';
// Push the key already used into the keys already used array
keysAlreadyUsed.push( value1[0] );
});
// Output
console.log(filterString);
console.log(keysAlreadyUsed);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
jsFiddle: https://jsfiddle.net/6oxc8umz/2/
Maybe is not the most efficient.
The first call of function reduce for creating a key-value object and the second call for generating the queryString.
let arrayTest = [['product_size', 123], ['product_size', 456] ,['product_color', 123]],
result = Object.entries(arrayTest.reduce((a, [key, value]) => {
if (a[key]) a[key] += `+${String(value)}`;
else a[key] = value;
return a;
}, Object.create(null))).reduce((a, [key, value]) => a + `${key}=${value}&`, "").slice(0, -1);
console.log(result);
First I'd turn the array into an object so you can associate the key to the concatenated values. Because you're using jQuery, you can utilize $.param to format it as you need to.
const arrayTest = [['product_size', 123],['product_size', 456],['product_color', 123]];
const toFilterString = obj => decodeURIComponent($.param(obj));
let params = arrayTest.reduce((output, [key,value]) => {
if (output[key]) output[key] += `+${value}`; //if key exists, concatenate value
else (output[key]) = value; //else, set value
return output;
}, {});
console.log(toFilterString(params));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
If you need the value to be URL-encoded, you can remove decodeURIComponent(...).
I want to fetch a particular value from a javascript string without using methods like indexOf or substr. Is there any predefined method of doing so?
For e.g., I have a string,
var str = "a=1|b=2|c=3|d=4|e=5|f=6";
I want to fetch the value of c from above string, how can I achieve it directly?
You can try with:
str.split('|').find(value => value.startsWith('c=')).split('=')[1]
You can also convert it into an object with:
const data = str.split('|').reduce((acc, val) => {
const [key, value] = val.split('=');
acc[key] = value;
return acc;
}, {});
data.c // 3
In this case, use split:
var str = "a=1|b=2|c=3|d=4|e=5|f=6";
var parts = str.split('|');
var value = parts[2].split('=')[1];
console.log(value);
Or maybe map it, to get all values to work with afterwards:
var str = "a=1|b=2|c=3|d=4|e=5|f=6";
var values = str.split('|').map(e => e.split('='));
console.log(values);
Using regex can solve this problem
const str = "a=1|b=2|c=3|d=4|e=5|f=6";
const matches = str.match(/c=([0-9]+)/);
console.log(matches[1]);
Ref:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match
Try this -
var str = "a=1|b=2|c=3|d=4|e=5|f=6";
str.split('|')[2].split('=')[1];
You could turn that string into an associative array or an object
var str = "a=1|b=2|c=3|d=4|e=5|f=6";
var obj = {}; //[] for array
str.split("|").map(o => {
var el = o.split("=");
obj[el[0]] = el[1];
})
console.log(obj.a)
console.log(obj.b)
console.log(obj.c)
I suggest first splitting and mapping into some form of readable data structure. Finding by string is vulnerable to typos.
const mappedElements = str
.split('|')
.map(element => element.split('='))
.map(([key, value]) => ({ key: value }));
Array filter method can be memory efficient for such operation.
var cOutput = str.split('|').filter( (val) => {
const [k,v] = val.split('=');
return k=='c' ? v : false }
)[0].split('=')[1];
See Array Filter
Is there a more functional way to create an object in JavaScript programatically without assigning each key individually?
For example, given this array (imagine it comes from an outside data source):
let arr = ['a=1', 'b=2', 'c=3'];
What is an easy way to convert this to an object like so?
let expectedResult = { a: '1', b: '2', c: '3'};
It's clunky to assign a new object and loop over the elements with a for or foreach. It would be nice if there were something akin to map that could yield such a final result.
Imagine you could do this:
arr
.map(item => new KeyValuePair(itemKey, itemValue)) // magically get itemKey/itemValue
.toObjectFromKeyValuePairs();
That'd be it right there. But of course there's no such function built in.
If you're looking for a more functional approach to the code, you could use a library such as Lodash which makes code more succinct.
You could use _.fromPairs to convert pairs of data in arrays to key-value pairs of an object.
const convert = arr => _(arr)
.map(s => _.split(s, '=', 2))
.fromPairs()
.value();
console.log(convert(['a=1', 'b=2', 'c=3']));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
You could use reduce, split and slice:
var arr = ['a=1', 'b=2', 'c=3'];
var out = arr.reduce(
function (output, input) {
if (typeof input === 'string') {
var key = input.split('=',1)[0];
output[key] = input.slice( key.length + 1 );
}
return output;
},
{}
);
I use the second argument of split to make it stop after the first = found. Then using slice on the input (treating it as an array of characters) allows the value to contain the = separator as in the case of a=b=c.
By using slice, the value will always be a string, even if it is an empty one. If you want to have null values you could change the line to:
output[key || null] = input.slice( key.length + 1 ) || null;
The type check for string is present since split throws error on null and undefined.
If you wanted to parse the current page's query string for example, you could do it using the above technique just like this:
function getQueryStringParams() {
var reEncodedSpace = /\+/g;
return location.search.length > 1 // returns false if length is too short
&& location.search.slice( 1 ).split( '&' ).reduce(
( output, input ) => {
if ( input.length ) {
if ( output === false ) output = {};
input = input.replace( reEncodedSpace, ' ' ); //transport decode
let key = input.split( '=', 1 )[ 0 ]; // Get first section as string
let value = decodeURIComponent( input.slice( key.length + 1) ); // rest is value
key = decodeURIComponent( key ); // transport decode
// The standard supports multiple values per key.
// Using 'hasOwnProperty' to detect if key is pressent in output,
// and using it from Object.prototype instead of the output object
// to prevent a key of 'hasOwnProperty' to break the code.
if ( Object.prototype.hasOwnProperty.call( output, key ) ) {
if ( Array.isArray( output[ key ] ) ) {
// Third or more values: add value to array
output[ key ].push( value );
} else {
// Second value of key: convert to array.
output[ key ] = [ output[ key ], value ];
}
} else {
// First value of key: set value as string.
output[ key ] = value;
}
}
return output;
},
false
);
}
The function returns false if the search is empty.
If you're willing to spare having one additional line for declaration, this could work for you. Although using a library like lodash or underscore, as mentioned in other answers would certainly help:
var arr = ['a=1', 'b=2', 'c=3'];
var expectedResult = {};
arr.map(function(value) {
var kv = value.split("=");
expectedResult[kv[0]] = kv[1];
return value
})
Try The Below Code.
let arr = ['a=1', 'b=2', 'c=3'];
let b=arr.toString();
b='{"'+(b.split('=').join('":"').split(',').join('","'))+'"}';
b=$.parseJSON(b);
console.log(b);
You will get the required output.
Is there a way to convert this object:
{
lang: 'en-us',
episode: 12
}
To a string with the following format?
"lang=en-us&episode=12"
Much like mapping an object to a query string, where each property is a query parameter.
I can do it like this:
var parameters = [];
for(var prop in obj)
parameters.push(prop + '=' + obj[prop]);
return parameters.join('&');
But I was looking for a one-line solution. Is this possible?
PS: I cannot use jQuery and any of it utility functions. The solution must be in pure JavaScript.
You can use Array.prototype.map on the Object.keys array:
var data = {"lang": "en-us", "episode": 12};
var str = Object.keys(data).map(function (key) {
return "" + key + "=" + data[key]; // line break for wrapping only
}).join("&");
console.log(str);
With ES6, this becomes even more terse:
var data = {"lang": "en-us", "episode": 12};
var str = Object.keys(data).map(key => `${key}=${data[key]}`).join("&");
console.log(str);
You could use
var myObj ={"lang": "en-us", "episode": 12};
var str = Object.keys(myObj).map(key => key+"="+myObj[key]).join("&");
Whether or not this is any more readable is another question :)
All the other answers work perfectly,
However I've found that you can use URLSearchParams for the same thing...
var myObj = {keyOne: 'keyOneValue', keyTwo: 'keyTwoValue'};
var queryParams = new URLSearchParams(myObj).toString();
console.log(queryParams);
// keyOne=keyOneValue&keyTwo=keyTwoValue
see: https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams
Object.entries (ES6)
Object.entries returns [key, value] pairs, so we can destructure and map the pairs directly into ${key}=${value}:
Object.entries(params).map(([key, value]) => `${key}=${value}`).join('&');
// "lang=en-us&episode=12"
URLSearchParams
For the specific use case of query strings, use URLSearchParams.toString:
let searchParams = new URLSearchParams(params);
searchParams.toString();
// "lang=en-us&episode=12"
URLSearchParams provides an interface with common utility methods, e.g.:
searchParams.get('episode');
// "12"
searchParams.sort();
// "episode=12&lang=en-us"
searchParams.set('episode', 123456);
// "episode=123456&lang=en-us"
If the value contains equalTo (=) symbol, the accepted solution will not work.
Example
key1=a,key2=b,keyc=keyof=thec
accesskey=absdsfdfsa===
Solution:
Better to use Regex,
const a =
'AccountName=devstoreaccount1;AccountKey=Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==;DefaultEndpointsProtocol=http;BlobEndpoint=http://127.0.0.1:10000/devstoreaccount1;QueueEndpoint=http://127.0.0.1:10001/devstoreaccount1;TableEndpoint=http://127.0.0.1:10002/devstoreaccount1';
const output = {};
a.split(';').forEach((v, i) => {
const [key, value] = v.split(RegExp(/=(.*)/));
output[key] = value;
})
console.log(output);
output
Note: AccountKey contains == in value
{
AccountName: 'devstoreaccount1',
AccountKey: 'Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==',
DefaultEndpointsProtocol: 'http',
BlobEndpoint: 'http://127.0.0.1:10000/devstoreaccount1',
QueueEndpoint: 'http://127.0.0.1:10001/devstoreaccount1',
TableEndpoint: 'http://127.0.0.1:10002/devstoreaccount1'
}
Pretty straight forward. In javascript, I need to check if a string contains any substrings held in an array.
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}"`);
}
Regular expression
If you know the strings don't contain any of the characters that are special in regular expressions, then you can cheat a bit, like this:
if (new RegExp(substrings.join("|")).test(string)) {
// At least one match
}
...which creates a regular expression that's a series of alternations for the substrings you're looking for (e.g., one|two) and tests to see if there are matches for any of them, but if any of the substrings contains any characters that are special in regexes (*, [, etc.), you'd have to escape them first and you're better off just doing the boring loop instead. For info about escaping them, see this question's answers.
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 (new RegExp(substrings.join("|")).test(str)) {
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 (new RegExp(substrings.join("|")).test(str)) {
console.log(`Match using "${str}"`);
} else {
console.log(`No match using "${str}"`);
}
One line solution
substringsArray.some(substring=>yourBigString.includes(substring))
Returns true\false if substring exists\does'nt exist
Needs ES6 support
var yourstring = 'tasty food'; // the string to check against
var substrings = ['foo','bar'],
length = substrings.length;
while(length--) {
if (yourstring.indexOf(substrings[length])!=-1) {
// one of the substrings is in yourstring
}
}
function containsAny(str, substrings) {
for (var i = 0; i != substrings.length; i++) {
var substring = substrings[i];
if (str.indexOf(substring) != - 1) {
return substring;
}
}
return null;
}
var result = containsAny("defg", ["ab", "cd", "ef"]);
console.log("String was found in substring " + result);
For people Googling,
The solid answer should be.
const substrings = ['connect', 'ready'];
const str = 'disconnect';
if (substrings.some(v => str === v)) {
// Will only return when the `str` is included in the `substrings`
}
Here's what is (IMO) by far the best solution. It's a modern (ES6) solution that:
is efficient (one line!)
avoids for loops
unlike the some() function that's used in the other answers, this one doesn't just return a boolean (true/false)
instead, it either returns the substring (if it was found in the array), or returns undefined
goes a step further and allows you to choose whether or not you need partial substring matches (examples below)
Enjoy!
const arrayOfStrings = ['abc', 'def', 'xyz'];
const str = 'abc';
const found = arrayOfStrings.find(v => (str === v));
Here, found would be set to 'abc' in this case. This will work for exact string matches.
If instead you use:
const found = arrayOfStrings.find(v => str.includes(v));
Once again, found would be set to 'abc' in this case. This doesn't allow for partial matches, so if str was set to 'ab', found would be undefined.
And, if you want partial matches to work, simply flip it so you're doing:
const found = arrayOfStrings.find(v => v.includes(str));
instead. So if str was set to 'ab', found would be set to 'abc'.
Easy peasy!
var str = "texttexttext";
var arr = ["asd", "ghj", "xtte"];
for (var i = 0, len = arr.length; i < len; ++i) {
if (str.indexOf(arr[i]) != -1) {
// str contains arr[i]
}
}
edit:
If the order of the tests doesn't matter, you could use this (with only one loop variable):
var str = "texttexttext";
var arr = ["asd", "ghj", "xtte"];
for (var i = arr.length - 1; i >= 0; --i) {
if (str.indexOf(arr[i]) != -1) {
// str contains arr[i]
}
}
substringsArray.every(substring=>yourBigString.indexOf(substring) === -1)
For full support ;)
For full support (additionally to #ricca 's verions).
wordsArray = ['hello', 'to', 'nice', 'day']
yourString = 'Hello. Today is a nice day'.toLowerCase()
result = wordsArray.every(w => yourString.includes(w))
console.log('result:', result)
If the array is not large, you could just loop and check the string against each substring individually using indexOf(). Alternatively you could construct a regular expression with substrings as alternatives, which may or may not be more efficient.
Javascript function to search an array of tags or keywords using a search string or an array of search strings. (Uses ES5 some array method and ES6 arrow functions)
// returns true for 1 or more matches, where 'a' is an array and 'b' is a search string or an array of multiple search strings
function contains(a, b) {
// array matches
if (Array.isArray(b)) {
return b.some(x => a.indexOf(x) > -1);
}
// string match
return a.indexOf(b) > -1;
}
Example usage:
var a = ["a","b","c","d","e"];
var b = ["a","b"];
if ( contains(a, b) ) {
// 1 or more matches found
}
This is super late, but I just ran into this problem. In my own project I used the following to check if a string was in an array:
["a","b"].includes('a') // true
["a","b"].includes('b') // true
["a","b"].includes('c') // false
This way you can take a predefined array and check if it contains a string:
var parameters = ['a','b']
parameters.includes('a') // true
Best answer is here:
This is case insensitive as well
var specsFilter = [.....];
var yourString = "......";
//if found a match
if (specsFilter.some((element) => { return new RegExp(element, "ig").test(yourString) })) {
// do something
}
const str = 'Does this string have one or more strings from the array below?';
const arr = ['one', 'two', 'three'];
const contains = arr.some(element => {
if (str.includes(element)) {
return true;
}
return false;
});
console.log(contains); // true
Not that I'm suggesting that you go and extend/modify String's prototype, but this is what I've done:
String.prototype.includes()
String.prototype.includes = function (includes) {
console.warn("String.prototype.includes() has been modified.");
return function (searchString, position) {
if (searchString instanceof Array) {
for (var i = 0; i < searchString.length; i++) {
if (includes.call(this, searchString[i], position)) {
return true;
}
}
return false;
} else {
return includes.call(this, searchString, position);
}
}
}(String.prototype.includes);
console.log('"Hello, World!".includes("foo");', "Hello, World!".includes("foo") ); // false
console.log('"Hello, World!".includes(",");', "Hello, World!".includes(",") ); // true
console.log('"Hello, World!".includes(["foo", ","])', "Hello, World!".includes(["foo", ","]) ); // true
console.log('"Hello, World!".includes(["foo", ","], 6)', "Hello, World!".includes(["foo", ","], 6) ); // false
building on T.J Crowder's answer
using escaped RegExp to test for "at least once" occurrence, of at least one of the substrings.
function buildSearch(substrings) {
return new RegExp(
substrings
.map(function (s) {return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');})
.join('{1,}|') + '{1,}'
);
}
var pattern = buildSearch(['hello','world']);
console.log(pattern.test('hello there'));
console.log(pattern.test('what a wonderful world'));
console.log(pattern.test('my name is ...'));
Drawing from T.J. Crowder's solution, I created a prototype to deal with this problem:
Array.prototype.check = function (s) {
return this.some((v) => {
return s.indexOf(v) >= 0;
});
};
Using underscore.js or lodash.js, you can do the following on an array of strings:
var contacts = ['Billy Bob', 'John', 'Bill', 'Sarah'];
var filters = ['Bill', 'Sarah'];
contacts = _.filter(contacts, function(contact) {
return _.every(filters, function(filter) { return (contact.indexOf(filter) === -1); });
});
// ['John']
And on a single string:
var contact = 'Billy';
var filters = ['Bill', 'Sarah'];
_.every(filters, function(filter) { return (contact.indexOf(filter) >= 0); });
// true
If you're working with a long list of substrings consisting of full "words" separated by spaces or any other common character, you can be a little clever in your search.
First divide your string into groups of X, then X+1, then X+2, ..., up to Y. X and Y should be the number of words in your substring with the fewest and most words respectively. For example if X is 1 and Y is 4, "Alpha Beta Gamma Delta" becomes:
"Alpha" "Beta" "Gamma" "Delta"
"Alpha Beta" "Beta Gamma" "Gamma Delta"
"Alpha Beta Gamma" "Beta Gamma Delta"
"Alpha Beta Gamma Delta"
If X would be 2 and Y be 3, then you'd omit the first and last row.
Now you can search on this list quickly if you insert it into a Set (or a Map), much faster than by string comparison.
The downside is that you can't search for substrings like "ta Gamm". Of course you could allow for that by splitting by character instead of by word, but then you'd often need to build a massive Set and the time/memory spent doing so outweighs the benefits.
convert_to_array = function (sentence) {
return sentence.trim().split(" ");
};
let ages = convert_to_array ("I'm a programmer in javascript writing script");
function confirmEnding(string) {
let target = "ipt";
return (string.substr(-target.length) === target) ? true : false;
}
function mySearchResult() {
return ages.filter(confirmEnding);
}
mySearchResult();
you could check like this and return an array of the matched words using filter
I had a problem like this. I had a URL, I wanted to check if the link ends in an image format or other file format, having an array of images format. Here is what I did:
const imagesFormat = ['.jpg','.png','.svg']
const link = "https://res.cloudinary.com/***/content/file_padnar.pdf"
const isIncludes = imagesFormat.some(format => link.includes(format))
// false
You can check like this:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
var list = ["bad", "words", "include"]
var sentence = $("#comments_text").val()
$.each(list, function( index, value ) {
if (sentence.indexOf(value) > -1) {
console.log(value)
}
});
});
</script>
</head>
<body>
<input id="comments_text" value="This is a bad, with include test">
</body>
</html>
let obj = [{name : 'amit'},{name : 'arti'},{name : 'sumit'}];
let input = 'it';
Use filter :
obj.filter((n)=> n.name.trim().toLowerCase().includes(input.trim().toLowerCase()))
var str = "A for apple"
var subString = ["apple"]
console.log(str.includes(subString))