How to fetch a value from a string in javascript? - javascript

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

Related

How split string into separate variables based on several characters in Java Script

There is a String variable that comes value like the following.
"COMPANY=10^INVOICE_ID=100021^"
I need to get this into two variables like Company and InvoieId.
What will be possible ways to do that JS?
Here is a dynamic way. You can grab any value from obj.
const str = "COMPANY=10^INVOICE_ID=100021^"
const obj = {}
const strArr = str.split('^')
strArr.forEach(str => {
const [key, value] = str.split('=')
obj[key] = value
})
const {COMPANY, INVOICE_ID } = obj
console.log(INVOICE_ID, COMPANY)
We can also do it via regular expression
Regex101 demo
let str = `COMPANY=10^INVOICE_ID=100021^`
let regex = /(\w+)=\d+/g
let match = regex.exec(str)
while(match){
console.log(match[1])
match = regex.exec(str)
}
If this code will be called more than once, let's create a function:
const parseInput = (input) => {
const [company, invoice_id] =
input.split("^")
.map(kv => kv.split("=")[1]);
return {
company,
invoice_id
};
}

How do I parse a string and get next 6 characters?

I have string like:
let str = "Hello=322484^nicetomeetyou=245454^howdoIdothis=11111a^EP";
how do I parse this string to get for example only "245454" ? I assume it must be based on 'nicetomeetyou=' the value after '=' is always 6 characters.
You can use split to extract the parts (name and value), and Object.fromEntries to turn those pairs into an object. Then you can access each value by property of that object:
const toObject = (str) =>
Object.fromEntries(str.split("^").map(eq => eq.split("=")));
// Demo
let str = "Hello=322484^nicetomeetyou=245454^howdoIdothis=11111a^EP";
let obj = toObject(str);
console.log(obj.Hello);
Note that in the example string, EP has no corresponding =, and in that case the object returned by toObject will have undefined assigned to the property EP. To test whether that EP property actually exists, you can use the in operator:
const toObject = (str) =>
Object.fromEntries(str.split("^").map(eq => eq.split("=")));
// Demo
let str = "Hello=322484^nicetomeetyou=245454^howdoIdothis=11111a^EP";
let obj = toObject(str);
console.log("EP" in obj); // true
So you reinvented querysting with a different separator. Make it an & and you can just use built in URLSearchParams
const str = "Hello=322484^nicetomeetyou=245454^howdoIdothis=11111a^EP";
const urlParams = new URLSearchParams(str.replace(/\^/g, '&'));
console.log(urlParams.get("Hello"));
console.log(urlParams.get("nicetomeetyou"));
console.log(urlParams.get("howdoIdothis"));
If you want to keep it with the ^, a split and map
var str = "Hello=322484^nicetomeetyou=245454^howdoIdothis=11111a^EP";
const params = Object.fromEntries(str.split("^").map(s => s.split(/=/)));
console.log(params["Hello"]);
console.log(params["nicetomeetyou"]);
console.log(params["howdoIdothis"]);
If you only care about the 3 values
var str = "Hello=322484^nicetomeetyou=245454^howdoIdothis=11111a^EP"
var re = /=([^\^]+)/g;
var out = [];
while(match = re.exec(str)) out.push(match[1]);
console.log(out);
And since you only seem to care about one value
const str = "Hello=322484^nicetomeetyou=245454^howdoIdothis=11111a^EP";
const val = str.match(/nicetomeetyou=(.{6})/)[1]
console.log(val);
You could replace all the ^ values with & and run it through URLSearchParams to get the value that you are looking for:
const str = "Hello=322484^nicetomeetyou=245454^howdoIdothis=11111a^EP";
const params = new URLSearchParams(str.replace(/\^/g, '&'))
console.log(params.get('nicetomeetyou'))

How to turn a string onto a map?

I need to turn a string formatted like that:
string = "John:31,Miranda:28"
Onto this;
obj = { "John" => 31, "Miranda" => 28 }
I did this :
const class = new Map();
array = string.split(",");
And obviously I do not know what do with it because after the split I get something like this:
["John:31", "Miranda:28"]
And I don't know how to turn it onto an object (using the ":" as a arrow)... Maybe I don't need to use the array as an intermediary? Any thoughts? Thanks
You can use split to split by comma, and then map on the resulting strings to split again by colon, and feed the resulting array of arrays into the Map constructor.
For instance, if you want the map keyed by the names, which I suspect you do:
const string = "John:31,Miranda:28"
const map = new Map(string.split(",").map(entry => entry.split(":")));
console.log(map.get("John")); // "31" (a string)
If you want the numbers to be numbers, not strings, you'll need to convert them:
const string = "John:31,Miranda:28"
const map = new Map(string.split(",").map(entry => {
const parts = entry.split(":");
parts[1] = +parts[1];
return parts;
}));
console.log(map.get("John")); // 31 (a number)
My answer here goes into some detail on your options for converting from string to number.
If you want the map keyed by value instead (which I suspect you don't, but...), you just have to reverse the order of the inner array entries:
const string = "John:31,Miranda:28"
const map = new Map(string.split(",").map(entry => {
const [name, num] = entry.split(":");
return [num, name];
}));
console.log(map.get("31")); // John
So split on the commas, loop over it and split on the colon, and build the object.
var myString = "John:31,Miranda:28"
var myObj = myString.split(',').reduce(function (obj, part) {
var pieces = part.split(':')
obj[pieces[0]] = pieces[1]
return obj
}, {})
You could try something like this:
const data = "John:31,Miranda:28"
const splitData = data.split(',')
const result = splitData.reduce((newObject, item) => {
const [name, age] = item.split(':')
return {
...newObject,
[name]: parseInt(age)
}
}, {})
console.log(result)
I'll just add this here:
Basically, split string by the comma, then the colon.
Combine result into a map
const test = "John:31,Miranda:28";
console.log(test);
const obj = test.split(/,/).map(item => item.split(/:/));
console.log(obj);
const _map = new Map(obj);
console.log(_map);
console.log(_map.get("John"))

What is a concise way to parse a javascript string that is a comma delimited list of key=value pairs?

I'm trying to parse a string into a JavaScript array or map. The string I'm trying to parse looks like:
"{key1=value1, key2=value2, key3=value3}"
The code I currently have works, but it's a bit lengthy.
str = "{key1=value1, key2=value2, key3=value3}";
str = str.replace(/{/g, '');
str = str.replace(/}/g, '');
var strMap = {};
str.split(', ').forEach(function(x) {
var arr = x.split('=');
strMap[arr[0]] = arr[1];
});
console.log(strMap)
That gets me what I want, but it's not very clean. Someone suggested I use JSON.parse, but it doesn't seem to work as the string isn't in valid JSON format.
Is there a concise way to do it so I'm not manually parsing the string?
You could split the string by comma and whitespace and splir key/value pairs for the properties of the new object. The result has strings as value.
const getPair = ([k, v]) => ({ [k]: v });
var string = "{key1=value1, key2=value2, key3=value3}",
result = Object.assign(...string
.slice(1, -1)
.split(/,\s+/)
.map(p => getPair(p.split('=')))
);
console.log(result);
Or take (upcoming) Object.fromEntries.
const getPair = ([k, v]) => ({ [k]: v });
var string = "{key1=value1, key2=value2, key3=value3}",
result = Object.fromEntries(string
.slice(1, -1)
.split(/,\s+/)
.map(p => p.split('='))
);
console.log(result);
You can use some ES6 features to pretty easily put together a decent naive solution (format as outlined by your example).
const example = "{key1=value1, key2=value2, key3=value3}";
const stripped = example.substring(1, example.length - 1);
const map = stripped.split(",")
.map(pair => pair.trim())
.reduce((result, current) => {
const [key, value] = current.split("=");
return {
...result,
key: value
};
}, {});

Converting a String to Multiple objects (javascript)

I have the following string: Jack:13,Phil:15,Lucy:12I'm trying to fetch objects from this string.
This string would have 3 people objects with their ages. How can this be achieved?
I've tried the following:
var s = 'Jack:13,Phil:15,Lucy:12'
var obj1 = eval("("+s+")");
var obj2 = JSON.parse(s);
Logging any of the obj variables returns errors. Am I missing a simple trick here? Any explanation would be appreciated, thanks.
In general, if you're doing replaces on a string to turn it into something you can pass eval or JSON.parse, that's probably not your best approach. An in particular, avoid using eval (or its cousin new Function) when you can (you certainly can here), and always avoid eval (or its cousin new Function) with untrusted input.
A pair of splits with map does it:
const s = 'Jack:13,Phil:15,Lucy:12'
const people = s.split(",")
.map(e => e.split(":"))
.map(([name, age]) => ({name, age}));
console.log(people);
...or in ES5:
var s = 'Jack:13,Phil:15,Lucy:12'
var people = s.split(",")
.map(function(e) { return e.split(":"); })
.map(function(e) { return {name: e[0], age: e[1]}; });
console.log(people);
I'm not sure why I did two maps rather than just doing the second split and creating the object in the same callback; I guess I'm thinking more and more in a "functional programming" way. I'd change it, but Eddie's answer already does it in a single map, so...
...(edit) but since it looks like you wanted separate properties rather than using the person's name like Eddie did, here's an example of the above but with just a single map:
const s = 'Jack:13,Phil:15,Lucy:12'
const people = s.split(",")
.map(e => {
const [name, age] = e.split(":");
return {name, age};
});
console.log(people);
...or in ES5:
var s = 'Jack:13,Phil:15,Lucy:12'
var people = s.split(",")
.map(function(e) {
var parts = e.split(":");
return {name: parts[0], age: parts[1]};
});
console.log(people);
You can split() the string and use map() to loop thru the array. This will return an array of objects.
var s = 'Jack:13,Phil:15,Lucy:12';
var result = s.split(',').map(o => {
let [k, v] = o.split(':');
return {[k]: v};
});
console.log(result);
If you want a single object, you can use reduce
var s = 'Jack:13,Phil:15,Lucy:12';
var result = s.split(',').reduce((c, o) => {
let [k, v] = o.split(':');
return Object.assign(c, {[k]: v});
}, {});
console.log(result);
You can try with:
const result = s.split(',')
.map(value => value.split(':'))
.reduce((acc, [name, value]) => {
acc[name] = +value;
return acc;
}, {});
Output:
{
"Jack": 13,
"Phil": 15,
"Lucy": 12
}
As I'm sure you've worked out there are many ways to do this, I thought I'd add another method
let s = 'Jack:13,Phil:15,Lucy:12'
let obj = {};
s.split(",").forEach(part => {
obj[part.split(":")[0]] = part.split(":")[1];
})
console.log(obj);
This is a simple split the string and then on each item of the new array do a split and push the results into an empty object already declared.
You could split the parts and build a new object with key/value pairs.
var string = 'Jack:13,Phil:15,Lucy:12',
result = Object.assign(...string
.split(',')
.map(s => (([k, v]) => ({ [k]: v }))(s.split(':')))
);
console.log(result);
For getting an array with objects
var string = 'Jack:13,Phil:15,Lucy:12',
result = string
.split(',')
.map(s => (([name, age]) => ({ name, age }))(s.split(':')));
console.log(result);
Easy to do with .map():
var s = 'Jack:13,Phil:15,Lucy:12';
var items = s.split(',')
.map((entry) => entry.split(':'))
.map((item) => ({name: item[0], age: item[1]}));
console.log(items);

Categories