Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

parse a string in javascript by a common delimiter

In javascript I have a string of the form "/john/smith". I'd like to get the array "first-name" : "john", "last-name" : "smith".

Does js have some easy function to parse this string based on a seperator? I haven't seen any and google returned nothing except doing some regex.

like image 287
Don P Avatar asked Nov 21 '25 10:11

Don P


2 Answers

var str="/john/smith"
var ar=str.split("/");

now ar[1] will contain firstname

& ar[2] will contain lastname

like image 123
bugwheels94 Avatar answered Nov 22 '25 23:11

bugwheels94


Something like this?:

var str = "/john/smith";

//empty is here because if you split by / you'll get ["", "john", "smith"]
var getObject = function(empty, first, last) {
    //You could traverse arguments, witch will have every match in an "array"
    return {
       first_name: first,
       last_name: last
    };
}

firstAndLastName = getObject.apply(null, str.split('/')); //Object {first_name: "john", last_name: "smith"}
like image 22
nicosantangelo Avatar answered Nov 22 '25 23:11

nicosantangelo