Disclaimer: I realize asking “Why doesn’t my regular expression work” is pretty amateur.
I have looked at the documentation, though I’m just plain struggling. I have a url (as a string) and what I want is to replace the placeholders (i.e. {objectID} and {queryTerm}
For a while now, I’ve been making attempts like this:
var _serviceURL = "http://my-server.com/rest-services/someObject/{objectID}/entries?term={queryTerm}";
var re1 = new RegExp("/{([A-Za-z])+}","gi");
var re2 = new RegExp("/{([A-Za-z]+)}+","gi");
var re3 = new RegExp("/{([A-Za-z])+}","gi");
var re4 = new RegExp("/({[A-Za-z]+})+","gi");
var re5 = new RegExp("({[A-Za-z]+})+","gi");
var re6 = new RegExp("({[A-Za-z]}+)*","g");
var re6a = new RegExp("({([a-z]+)})+","gi");
var re7 = /{([^}]+)}/g;
var tokens = re6A.exec(_serviceURL);
if (null != tokens.length ){
for(i = 0; i < tokens.length; i++){
var t = tokens[i];
console.log("tokens[i]: " + t);
}
}
else {
console.log("RegEx fail...")
}
re6a above produces an array like this upon execution:
tokens: Array[3]
0: "{objectID}"
1: "{objectID}"
2: "objectID"
Related to the scenario above:
- Why is it I’m never getting the
queryTerm? - Does the RegExp ‘i’ (ignore case) flag mean I can list a character class like [a-z] and also capture [A-Z] ?
- Which method of constructing a RegExp object is better?
...new RegExp(...);orvar regExp = /{([^}]+)}/g;. In terms of “what’s better”, what I mean is cross-browser compatibility and as similar to other RegEx implementations (if I’m learning RegEx, I want to get the most value I can out of it).
Yes, it’ll capture them all.
You should definitely use the literal notation.
It gets compiled once at runtime, instead of every time you use it.
They’re both equally cross browser compatible.
All that said, I’d use this:
Here’s the fiddle: http://jsfiddle.net/CAugU/
Here’s an explanation of the above regex: