admin管理员组

文章数量:1315090

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.

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.

Share Improve this question asked Jun 20, 2013 at 4:19 Don PDon P 63.8k121 gold badges318 silver badges447 bronze badges
Add a ment  | 

6 Answers 6

Reset to default 3
var str="/john/smith"
var ar=str.split("/");

now ar[1] will contain firstname

& ar[2] will contain lastname

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"}

You can use the .split() method for this. See the MDN for a reference on .split(): https://developer.mozilla/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split

It's very simple to use.

var namestring = "/John/Smith";
var pieces = namestring.split("/");

pieces[1] contains "John" and pieces[2] contains "Smith". Note that those index arrays are 1 and 2, not 0 and 1. pieces[0] contains "" because split() returns the strings separated by the supplied delimiter. There's an empty string before the first "/" character, so the first result is empty.

split() method will do the trick

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

arr[1] will give forstname and arr[2] will give secondname

The simple Javascript split method should work.

var myOriginalString = '/John/Smith';
var afterSplitArray = myOriginalString.split('/');
var firstName = afterSplitArray[1]; // John
var lastName = afterSplitArray[2]; //Smith

The only catch being, if your original string starts with the delimiter, you've to start accessing variables from index = 1, as in the above example.

A few ways to do this for your particular example, given that most other answers will leave a / at the beginning these will output the correct result:

var result = str.match(/[^/]+/g);

Or:

var result = str.split('/').slice(1);

本文标签: regexparse a string in javascript by a common delimiterStack Overflow