I have a string something like var myStr = 'Foo Faa {{Foo1234Faa789863Whateva}}'. I don't know what is there between the braces and I want to find out substring '{{Foo1234Faa789863Whateva}}' by doing something like myStr.search('{{anycharacter}}'). Please help me how I can do this?
Add a comment
|
2 Answers
Use this
var myStr = 'Foo Faa {{Foo1234Faa789863Whateva}}'
var match = myStr.match(/{{(.*)}}/)
if (match) {
console.log(match[1]);
}
3 Comments
AxelH
simple, just need to know how to react if you found {{Foo1234Faa789863Whateva}}{{Foo1234Faa789863Whateva}} or {{Foo1234Faa789863Whateva {{Foo1234Faa789863Whateva}} }} to update your code. If the OP needs it of course ;)
kvn
Since the OP didn't mention anything about nesting. I think it is safe to assume that it is not needed.
AxelH
Yeah, I just hope he will read my comment and update if needed ;)
Addition to @SGSVenkatesh's answer
match() is a pretty good choice, but if you know that only the first match is what you want, you can use 2 split() functions instead match.
var myStr = 'Foo Faa {{Foo1234Faa789863Whateva}}';
var strSplit = myStr.split("{{");
var strSplit2 = strSplit[1].split("}}");
console.log(strSplit2[0]);
// logs "Foo1234Faa789863Whateva"
You can make it into a function as;
function getFirstMatch(beginsWith, endsWith, myStr){
var strSplit = myStr.split(beginsWith);
var strSplit2 = strSplit[1].split(endsWith);
return strSplit2[0];
}
//usage
console.log(getFirstMatch("{{", "}}", "Foo Faa {{Foo1234Faa789863Whateva}}"));
// logs "Foo1234Faa789863Whateva"
It just feels more efficient for me, did not do any test about which is better, post a comment if you do performance test ;)