How can I split a string into separate keys and values? - javascript

I have the following string:
myString = "Name:Joe Email:info#domian.com Details: I like Sushi";
I would like to split it out into separate variables like:
name = "Joe";
email = "info#domian.com";
details = "I like Sushi";
I tried something like the below, but it didn't account for everything.
myString = "Name:Joe Email:info#domian.com Details: I like Sushi";
splitString = myString.split(':');
myName = splitString[1];
myEmail = splitString[2];
myFood = splitString[3];
console.log('Name: ', myName);
console.log('Email: ', myEmail);
console.log('Food: ', myFood);
I'm wondering if there might be a creative way to do this in JS? Thanks.

This will turn your string into an object with key/value pairs using match() and split(). You can then access the variables using the object, like obj.name or obj.email. There may be a way to fix my regex so that the .shift() method isn't necessary, but it works nonetheless.
let myString = "Name:Joe Email:info#domian.com Details: I like Sushi";
let keys = myString.match(/\w+:/g)
let values = myString.split(/\w+:/);
values.shift(); // remove first item which is empty
let obj = {};
keys.forEach((key, index) => {
obj[key.replace(":", "").toLowerCase()] = values[index].trim()
})
console.log(obj)
// access variables like obj.name or obj.email

Try this:
myString = "Name:Joe Email:info#domian.com Details: I like Sushi";
splitString = myString.split(':');
myName = splitString[1].split(' ')[0];
myEmail = splitString[2].split(' ')[0];
myFood = splitString[3]
console.log(myName);
console.log(myEmail);
console.log(myFood);
If you want to get rid of the space in front of "I like Sushi":
details = splitString[3].split(' ');
myDetails = details[1] +' '+ details[2] +' '+ details[3]; console.log(myDetails);

var myString = "Name:Joe Email:info#domian.com Details: I like Sushi";
var arr = myString.replace(/:\s/g, ':').split(" "),
obj = {};
// .replace(/:\s/g,':') Or .replace(/[:\s]/g,':') whichever works better
for (var i = 0; i < arr.length; i++) {
var item = arr[i],
arr2 = item.split(":"),
key = arr2[0].toLowerCase();
obj[key] = arr2[1];
}
console.log(obj["email"]);
//info#domain.com
console.log(obj["details"]);
//I like Sushi

Related

How to split an array dynamically on the basis of keywords?

I have an array(prop1) and also a set of keywords(prop2). I want to be able to split the array as per the keywords so that it looks like the wordSet array. How do I split this? The number of words in prop1 and prop2 can vary.
prop1 = {"Hello World. I want to welcome you to my kingdom"}
prop2 = ['World', 'welcome', 'kingdom']
const wordSet =
[
"Hello ",
"World",
". I want to ",
"welcome",
" you to my ",
"kingdom"
]
arr.map((wordSet) => {
const isHighlighted = prop2.indexOf(wordSet) > -1;
return <span className={isHighlighted ? classes.highlighted : classes.other}>{wordSet}</span>
})
I'd construct a regular expression from the prop2s - make a RE that matches any characters until running into the keywords, and separately capture the matched keyword:
const prop1 = "Hello World. I want to welcome you to my kingdom";
const prop2 = ['World', 'welcome', 'kingdom'];
const pattern = new RegExp('(.*?)($|' + prop2.join('|') + ')', 'gi');
const wordSet = [...prop1.matchAll(pattern)]
.flatMap(m => [m[1], m[2]])
.filter(Boolean);
console.log(wordSet);
I'll do multi pass using split. I am not sure if it will work out well, but let me give a try!
var str = "Hello World. I want to welcome you to my kingdom";
var arr = ['World', 'welcome', 'kingdom'];
var final = [str];
for (var i = 0; i < arr.length; i++) {
final = final.flat(2).map(function (f) {
return f.split(arr[i]).join("aaaa" + arr[i] + "aaaa").split("aaaa");
}).flat(2).filter(a => a);
}
console.log(final);
There could be possibly the aaaa might be a part of the word or the array, that's the only caveat I have got here. But we can switch it using something like this:
var str = "Hello World. I want to welcome you to my kingdom";
var arr = ['World', 'welcome', 'kingdom'];
var final = [str];
for (var i = 0; i < arr.length; i++) {
final = final.flat(2).map(function (f) {
// Not fool proof.
var sep = str.indexOf("aaaa") > -1 ? "bbbb" : "aaaa";
return f.split(arr[i]).join(sep + arr[i] + sep).split(sep);
}).flat(2).filter(a => a);
}
console.log(final);

Replace string with array elements

let string = 'My name is [~FIRSTNAME] [~LASTNAME]';
let nameArray = ['Peter', 'Parker'];
let patternToBeReplaced = ['[~FIRSTNAME]', '[~LASTNAME]']
I want to replace the string with the elements of namearray so that the string becomes 'My name is Peter Parker'
Below is my approach to this problem -
patternToBeReplaced.forEach(function (match, index) {
var output = string.replace(match, nameArray[index]);
});
But this is not working as expected.
You could use Array#reduce and use the string for the next replacement.
let string = 'My name is [~FIRSTNAME] [~LASTNAME]';
let nameArray = ['Peter', 'Parker'];
let patternToBeReplaced = ['[~FIRSTNAME]', '[~LASTNAME]']
string = patternToBeReplaced.reduce((s, m, i) => s.replace(m, nameArray[i]), string);
console.log(string);
You're creating a string templating system. Since you're using ECAMScript 6 syntax already, you could use the new built-in template literals.
let [FIRSTNAME, LASTNAME] = ['Peter', 'Parker'];
let string = `My name is ${FIRSTNAME} ${LASTNAME}`;
console.log(string);
This will also work more cleanly when there are multiple insertions of a given label within the string.
let [FIRSTNAME, LASTNAME] = ['Peter', 'Parker'];
let string = `My name is ${LASTNAME}... ${FIRSTNAME} ${LASTNAME}`;
console.log(string);
patternToBeReplaced.forEach(function (match, index) {
string = string.replace(match, nameArray[index]);
});
Something like that.
let str = 'My name is [~FIRSTNAME] [~LASTNAME]';
let nameArray = ['Peter', 'Parker'];
let patternToBeReplaced = ['[~FIRSTNAME]', '[~LASTNAME]']
const result = patternToBeReplaced.reduce((str, placeholder, i) => {
return str.replace(placeholder, nameArray[i]);
}, str);
console.log(result);
output is a local variable, it's useless to just declaring it.
replace(String, String) would only replace the first matched pattern.
Here's my solution:
let replaceWithArrayElements = (patterns, replacements, targetString) => {
patterns.forEach((pattern, i) => targetString = targetString.replace(new RegExp(pattern, 'g')));
return targetString;
}
First solution, keeping your base code :
let string = 'My name is [~FIRSTNAME] [~LASTNAME]';
let nameArray = ['Peter', 'Parker'];
let patternToBeReplaced = ['[~FIRSTNAME]', '[~LASTNAME]'];
patternToBeReplaced
.forEach((match, i)=>{
string = string
.replace(match, nameArray[i]);
});
Using Map:
let string = 'My name is [~FIRSTNAME] [~LASTNAME]';
let replaceMap = new Map();
replaceMap.set('[~FIRSTNAME]', 'Peter');
replaceMap.set('[~LASTNAME]', 'Parker');
replaceMap.forEach((key, value)=>{
string = string.replace(key, value);
});
Using ES6 "template" strings:
/*
*Have some ways of getting the first name in "firstName"
*Have some ways of getting the last name in "lastName"
*/
let string = `My name is ${firstName} ${lastName}`;
string.match(/\[~\w+\]/g).forEach((item,index)=>{
string = string.replace(item, nameArray [index])
})
You can use the above code for you needs

How to extract page category and variable names into array from URL in Javascript

I have a link like this:
https://example.com/category?variable1=value1&variable2=value2
and I need to extract page category and variable names and save it into variable and into array of variable names:
category = "category";
array = ["variable1", "variable2"];
Any sugestions how can I achieve it using Javascript?
If your link is a string like the one you reported a simple solution can be based on:
str.split([separator[, limit]]) where as separator you can use a regex
array.splice(start, deleteCount) in order to remove the first and last ele
The example:
var str = 'https://example.com/category?variable1=value1&variable2=value2';
var res = str.substr(str.lastIndexOf('/') + 1).split(/[?]|=[^&]*&{0,1}/);
var category = res[0];
var arr = res.splice(1, res.length - 2);
console.log(category);
console.log(arr);
If an object works for you as well here is a solution:
//Get variables into an object
function uriToJson (url) {
const regx = /(\?|&)([^=]+)=([^&]+)/g;
const index = url.search(regx) + 1;
const params = url.substring(index);
return JSON.parse(`{"${decodeURI(params)
.replace(/"/g, '\\"')
.replace(/&/g, '","')
.replace(/=/g, '":"')}"}`);
}
const url = 'https://example.com/category?variable1=value1&variable2=value2'; //window.location.href...
const obj = uriToJson(url);
console.log(obj);
//Get category into a variable
var stepone = url.substring(0,url.indexOf('?'));
var steptwo = stepone.substring(stepone.indexOf('m/') + 1 )
var category = steptwo.replace('/','');
console.log(category);

Regex for creating an array from String

I have a string as follows
var str = "[series-3,series-5,series-6],[a3,a4,a5],[class a,class b]";
I want to get three arrays from above string as follows
var arr1 = ["series-3","series-5","series-6"];
var arr2 = ["a3","a4","a5"];
var arr3 = ["class a", "class b"];
What regex should I use to achieve this?
Can this be done without regex?
Use String#split() method
var str = "[series-3,series-5,series-6],[a3,a4,a5],[class a,class b]";
// split string based on comma followed by [
var temp = str.split(/,(?=\[)/);
// remove [ and ] from string usning slice
// then split using , to get the result array
var arr1 = temp[0].slice(1, -1).split(',');
var arr2 = temp[1].slice(1, -1).split(',');
var arr3 = temp[2].slice(1, -1).split(',');
console.log(arr1, arr2, arr3);
Or same method with some variation
var str = "[series-3,series-5,series-6],[a3,a4,a5],[class a,class b]";
// Remove [ at start and ] at end using slice
// and then split string based on `],[`
var temp = str.slice(1, -1).split('],[');
// then split using , to get the result array
var arr1 = temp[0].split(',');
var arr2 = temp[1].split(',');
var arr3 = temp[2].split(',');
console.log(arr1, arr2, arr3);
RegEx and String methods can be used. It's better to create an object and store individual arrays inside that object.
var str = "[series-3,series-5,series-6],[a3,a4,a5],[class a,class b]";
// Match anything that is inside the `[` and `]`
var stringsArr = str.match(/\[[^[\]]*\]/g);
// Result object
var result = {};
// Iterate over strings inside `[` and `]` and split by the `,`
stringsArr.forEach(function(str, i) {
result['array' + (i + 1)] = str.substr(1, str.length - 2).split(',');
});
console.log(result);
var str = "[series-3,series-5,series-6],[a3,a4,a5],[class a,class b]";
var stringsArr = str.match(/\[[^[\]]*\]/g);
var result = {};
stringsArr.forEach(function(str, i) {
result['array' + (i + 1)] = str.substr(1, str.length - 2).split(',');
});
console.log(result);
To create the global variables(Not recommended), just remove var result = {}; and replace result by window in the forEach.
I would prefer to do it like this
var str = "[series-3,series-5,series-6],[a3,a4,a5],[class a,class b]",
arrs = str.match(/[^[]+(?=])/g).map(s => s.split(","));
console.log(arrs);
Just for the fun of it, another way where we add the missing quotes and use JSON.parse to convert it to a multidimensional array.
var str = "[series-3,series-5,series-6],[a3,a4,a5],[class a,class b]";
var result = JSON.parse("[" + str.replace(/\[/g,'["').replace(/\]/g,'"]').replace(/([^\]]),/g,'$1","') + "]");
console.log(result[0]);
console.log(result[1]);
console.log(result[2]);

how to split function in javascript

i have data in
var description="Name:John;EmployeeID:2;Salary:$8000;Address:London";
i want the result as
Name: John
Employee Id: 2
Salary: $8000
Address: London
is it possible with split() function in javascript?
You can do it with String.split() but in this case it's simpler to use String.replace():
var description="Name:John;EmployeeID:2;Salary:$8000;Address:London";
description = description.replace(/;/g, '\n').replace(/:/g, ': ');
/*
"Name: John
EmployeeID: 2
Salary: $8000
Address: London"
*/
If you want the result as an object, try:
var f = function (str) {
var x = {}, key2label = { EmployeeID: 'Employee Id' };
str.replace(/(.+?):(.+?)(;|$)/g, function (match, key, value) {
key = key2label[key] || key;
x[key] = value;
});
return x;
};
If a simple string is needed, but you still need to replace keys:
var f2 = function (str) {
var key2label = { EmployeeID: 'Employee Id' };
return str.replace(/(.+?):(.+?)(;|$)/g, function (match, key, value, semi) {
key = key2label[key] || key;
return key + ': ' + value + (semi ? '\n' : '');
});
};
If you really didn't mean to replace keys, this will do it:
var f3 = function (str) {
return str.split(':').join(': ').split(';').join('\n');
};
... or use Matt Ball's answer.
With this statement:
var arrDescription = description.split(";");
you will get an array with all the values. For more info on split check the following link.
you can even join them afterwards :
printf(arrDescription.join(" "));
For more info on join check the following link.
Max
You can probable try like this to display.
var description="Name:John;EmployeeID:2;Salary:$8000;Address:London";
var arr=new Array();
arr=description.split(";");
for(var i=0;i<arr.length;i++)
document.writeln("<h4>"+arr[i]+"</h4>");
Yes.
You first should split on the semicolon ;. Loop through those results, and split each result on each colon :.
You will have to build the result by hand.
var description="Name:John;EmployeeID:2;Salary:$8000;Address:London"; var splitted = description.split(";");
for(var i = 0; i < splitted.length; i++) { document.write(splitted[i] + ""); }

Categories