简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM