0

I've searched this place a lot, and I'm stuck at that my regular expression works, but not dynamically.

id_name is the string that is picked dynamically. Then, the regexp should replace the match with a single var, which is in "vals". For some reason, when I code the regexp without the variable, it works as intended. I think I might do something wrong with the conversion to a regexp object.

Original String:

obj = values.replace(/{name}(.*?){\/name}/, 'igm');

Regexp Object:

        re = '\/{' + id_name + '}(.*?){\\/' + id_name + '}\/';
        regexp = new RegExp(re, 'igm');
        obj = values.replace(regexp, vals);

Thanks in advance!

1
  • Didn't know it was that easy :), it worked perfectly! Thanks! Commented Jul 12, 2012 at 8:40

1 Answer 1

1

You don't need / and you also don't need to escape the character if you are constructing the regex via constructor:

re = '{' + id_name + '}(.*?){/' + id_name + '}';
Sign up to request clarification or add additional context in comments.

10 Comments

Worked really well. What I do not understand, and I've tried to cross check the reference on it, but saw nothing about: (regexp is still in my eyes one of the most difficult things) When I replace the { } for % and /%... it works fine the first time it comes across it, but the second time, it stops replacing: ` re = '%' + id_name+ '%(.*?)%/' + id_name + '%'; regexp = new RegExp(re, 'igm'); values = values.replace(regexp, ''); `
@user1520088: I don't know - it is possible that you have something strange in id_name that is recognized as regex.
I'm not certain it's what's in there. Since it replaces everything else fine. It's just when I replace the {} for %% when it goes wrong for the second time. I forced the id_name into a string. Even hardcoded, it has a problem. I have to add, whatever it's replacing is a email footer. The first part is purely text based with a <br> here and there. The second one has a TABLE layout. like %name%<tr><td>{name}John Doughnut{/name}</td></tr>%/name%. Whenever when unchecked the option, it suppose to remove the %name% section. Works in the first part, not second (within table).
Do you want to just remove %name% or do you want to remove everything inside including the %name?
Everything in between the %name% --- %/name% really :)
|

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.