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 badges6 Answers
Reset to default 3var 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
版权声明:本文标题:regex - parse a string in javascript by a common delimiter - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741972468a2407923.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论