//haystack example
const haystack = "cat=fluffy; dog=spot; cow=daisy"
//needle example
const needle = "cow"
//find function passing haystack and needle
const find = (haystack,needle) => {
//split string at the space between each and create an array
const splitHaystack = haystack.split(" ");
//map the splitted content and find the title and value
const searchterm = splitHaystack.map(obj => {
//find title by returning the word in between " and the =
const startTitle = obj.indexOf('"') + 1;
const endTitle = obj.indexOf('=',startTitle);
const title = obj.substring(startTitle,endTitle);
//find value by returning the word in between = and the ;
const startValue = obj.indexOf('=') + 1;
const endValue = obj.indexOf(';',startValue);
const value = obj.substring(startValue,endValue);
//find if needle and a title match then return value
const getvalue= needle === title ? value : null;
return getvalue;
});
//turn value into string, remove commas;
const valueInString = searchterm.toString();
const value = valueInString.replace(/,/g, '');
const print = value === "" ? "null": value
return print;
}
alert(find(haystack,needle));
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.