0

Hey all, having an issue doing string replacement for template engine code I am writing. If my tokens are 1 level deep everything works fine. Example {someProperty}. But if I try searching for a nested object it never does the replace. Example {myobj.deep.test}. I've attached the code I am playing around with. Thanks for the help!

function replaceStuff(content, fieldName, fieldValue) { 
    var regexstr = "{" + fieldName + "}";
    console.log("regexstr: ", regexstr);
    //var regex = new RegExp("{myobj\.deep\.test}", "g"); //this works as expected
    var regex = new RegExp(regexstr, "g"); //this doesn't
    return content.replace(regex, fieldValue);
}

replaceStuff("test: {myobj.deep.test}", "myobj.deep.test", "my value");
bluish
  • 26,356
  • 27
  • 122
  • 180
stuffins
  • 53
  • 1
  • 5
  • works fine for me in chrome... – josh.trow Feb 03 '11 at 16:20
  • What browser are you using? It works fine for me in Chrome 9, Firefox 4 b10, Opera 11, Safari 5, IE 8 and Firefox 3.6 (except the last two don’t recognize the `console` object). Checked with http://jsbin.com/etago3 – Martijn Feb 03 '11 at 17:11

2 Answers2

1

See this SO question about curly braces. Perhaps your browser of choice isn't as understanding as chrome is?

Community
  • 1
  • 1
josh.trow
  • 4,861
  • 20
  • 31
0

You need to escape the '.' characters in the string you're passing in as the fieldName parameter. Ditto for any other special regex characters that you want to be interpreted literally. Basically, fieldName is being treated as part of a regex pattern.

If you don't want fieldName to be evaluated as regex code, you might want to consider using string manipulation for this instead.

Edit: I just ran your code in FireFox and it worked perfectly. You may have something else going on here.

Justin Morgan - On strike
  • 30,035
  • 12
  • 80
  • 104
  • A dot matches any character, also dots. But of course its still a good idea to escape them in this case. – morja Feb 03 '11 at 16:22
  • @morja: That's a good point, my bad. I'll leave the answer up for now because it's still an issue with the code he's posted, but I'll look for another problem and edit my answer. – Justin Morgan - On strike Feb 03 '11 at 16:26
  • @morja, dots don't match newlines. – Mike Samuel Feb 03 '11 at 16:34
  • @Mike, true. At least for javascript as it does not have a "dot matches all" flag. But there is a library: XRegExp, it has a "s" flag to do it. – morja Feb 03 '11 at 16:41
  • 1
    @morja, Good to know about XRegExp. You might mention that when you say escape, you have to double up escapes when using the RegExp(string) constructor. `/\./` is not equivalent to `new RegExp('\.')` and `/\b/` is very different from `new RegExp('\b')`. – Mike Samuel Feb 03 '11 at 21:02