0

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?

2 Answers 2

3

Use this

var myStr = 'Foo Faa {{Foo1234Faa789863Whateva}}'
var match = myStr.match(/{{(.*)}}/)
if (match) {
    console.log(match[1]);
}
Sign up to request clarification or add additional context in comments.

3 Comments

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 ;)
Since the OP didn't mention anything about nesting. I think it is safe to assume that it is not needed.
Yeah, I just hope he will read my comment and update if needed ;)
2

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 ;)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.