how to use regular expression in javascript to extract value?
I want to use regular expression in javascript to extract values. The string is in this pattern "title{position}", how s开发者_JAVA百科hould i get title and position in this example?
Assuming that's all there is too it (no nesting of '{}'s or anything) (\w+)\{(\w+)\}
will match that instance and group the results as groups 1 and 2. Do you need anything more complicated like a collection of many of these per string or is that enough?
Is that string everything? If so there's no need for matching. Just split the string!
var str = "foo{bar}";
var pieces = str.split(/\{|\}/);
var title = pieces[0];
var position = pieces[1];
alert("Title: " + title + "\nPosition: " + position);
Demonstrated here
If you did want to add results to a structure -
var arr = [];
var text = 'title{position}';
text.replace(/(\w+){(\w+)}/g, function(m, key, value){
//alert('title is-'+key);
//alert('position is-'+value);
arr.push({"title":key,"position":value});
});
console.log(arr);
Demo - http://jsfiddle.net/Sr6Ed/1/
精彩评论