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'))
Related
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
};
}
For example:
str = "A=sample_text1; B=sample_text2; C=sample_text3;";
How can I get the text after "A=", which is "sample_text1" out ? (the length of sample_text1 can be very long, so str.substring won't work here)
Looks like your string has a structure where there are multiple fields where each field is represented as:
[KEY]=[VALUE];
You can use common string and array methods like split and map to extract what you need. In this case looks like you want the value of the first field:
const str = 'A=sample_text1; B=sample_text2; C=sample_text3;';
const result = str.split(';').map(s => s.split('=').pop().trim()).shift();
console.log(result); //=> 'sample_text1'
https://regexr.com is very useful for creating and testing regex.
const match = "A=sample_text1; B=sample_text2; C=sample_text3;".match(/A=([^;]*)/);
let value = match !== null ? match[1] : undefined;
Would allow you to get the value of A in this case
You could use a regular expression to capture every group surrounded by a = and a ;:
const str = "A=sample_text1; B=sample_text2; C=sample_text3;";
const regexp = "=(.*?);";
const values = [...str.matchAll(regexp)];
const aValue = values[0][1];
console.log(aValue);
It might be an overkill, but to easily access to all the keys / values, you could use Object.fromEntries:
let str = "A=sample_text1; B=sample_text2; C=sample_text3;";
let values = Object.fromEntries(
str
// Split all the pairs
.split(";")
// Remove the last empty element
.slice(0,-1)
// map to a [key, value] array to pass to Object.fromEntries
.map(i => i.split("=").map(j => j.trim())));
// get a value using a key
console.log(values["A"]) // sample_text1
// check if a key is present
console.log("C" in values) // true
console.log("D" in values) // false
It looks more longer than it is due the comments and the console logs, it can fit in one line.
Notice that this is assume of course that neither the character = or ; can be part of the key or the value.
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"))
I have a string that comes to me like this: "[value1][value2]"
How can I get the values that are inside the square brackets?
NOTE: if the string is like this "[][value2]" the first bracket that has a space must return a "" to me...
I have been trying a lot of regex and split but none workd.
this is the last I tried:
var pattern = /[([^]]*)]/g;
var res = pattern.exec(datos[0].title);
Another one I tried is:
var res = datos[0].title.match(/^.*?[([^]]*)].*?[([^]]*)]/gm);
but none do what I need...
I'm trying to find a way "that does it all" a regex that gets anything inside the Square brackets (even white spaces)
As #HarryCutts stated, you don't need regex:
var x = "[value1][value2]";
console.log( x.slice(1,-1).split('][') );
You can try this regex and the brute force way to extract the contents.
var regex = /\[(.*?)\]/g;
var value = "[value1][value2][]";
var matches = value.match(regex);
var matchedValues = matches.map(match => {
return match.replace("[", "").replace("]", "");
}).join(" ");
console.log(matchedValues.toString())
You could just do this:
var str = "['value1']['value2']";
var value1 = str.split("]")[0].split("[")[1];
var value2 = str.split("]")[1].split("[")[1];
console.log(str);
console.log(value1);
console.log(value2);
You can easily expand it for more values.
const string = "[value1][value2]";
const removeBrackets = (stringWithBrackets) => {
return stringWithBrackets.split("][").map(s => s = s.replace(/\[*\]*/g, ""));
};
const [value1, value2] = removeBrackets(string);
console.log(value1, value2);
const getItems = (fullItemsString) => {
let items = fullItemsString.replace(/\[/g, "").split("]");
items.pop()
return items;
}
Using:
let items = getItems("[2][][34][1]");
result: [ '2', '', '34', '1' ]
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