Search String Value

by Paola D'Antonio

JavaScript

//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));