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");
2
  • works fine for me in chrome... Commented Feb 3, 2011 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 jsbin.com/etago3 Commented Feb 3, 2011 at 17:11

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

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.

5 Comments

A dot matches any character, also dots. But of course its still a good idea to escape them in this case.
@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.
@morja, dots don't match newlines.
@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, 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').

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.