JavaScript RegEx $1 Tokens

masterjake

New Member
Messages
73
Reaction score
0
Points
0
Hi. I'm having a problem. I have various text fields with ID's of a letter and a number e.g. "A1", "C3", etc.

When this JavaScript function runs it is suppose to replace all occurrences of "{stuff here}" with the value at the cell number within the {}.

For example, if they type in "{A1}+{B2}" then the JavaScript should find {A1} and replace it with the value of the element who's ID is "A1."

Here is what I have. I know it's a problem with the "$1."

Code:
var editedExpression = eqvalue.replace(/\{(.+?)\}/g, document.getElementById("$1").value);
 

ah-blabla

New Member
Messages
375
Reaction score
7
Points
0
//UPDATE: Ignore this post, misson actually knows what he's on about, so read his post.

Where does the $1 come in other than that line?
I was wondering the same. If $1 is a variable, then remove the quotation marks around it, since here you are passing $1 as the name of an element. However, javascript variables aren't usually written with $ signs... Unless you are using a variable from php, in which case you would have to enclose it in <?php ?> tags if it is external, or add a . on either side of the $1 to concatenate it as part of a string you are doing something with.
 
Last edited:

misson

Community Paragon
Community Support
Messages
2,572
Reaction score
72
Points
48
document.getElementById(...) is being called before eqvalue.replace(...) (remember, in f(..., g(...), ...), the call to g(...) must be evaluated before f is called). The solution is to use an anonymous function:

Code:
var editedExpression = eqvalue.replace(/\{(.+?)\}/g, 
        function(matched, id) { return document.getElementById(id).value; });

The matched substrings are passed as parameters to the function; $& is passed in arguments[0] and $n in arguments[n].

Also note that the $n signifier for positional parameters is only supported in a few contexts: a regular expression and a plain string replacement. There are also properties of RegExp named $n that hold the matches from the last successful match; while they have the same signifiers, they're different beasts. "$n" has no special meaning within a function replacement.
 

masterjake

New Member
Messages
73
Reaction score
0
Points
0
Thanks man, that code worked.

In every other language I've used for RegEx replacement (generally by means of preg_replace), all of the returned (groups) were placed into $variables.

I figured JavaScript would be the same.
 

misson

Community Paragon
Community Support
Messages
2,572
Reaction score
72
Points
48
In every other language I've used for RegEx replacement (generally by means of preg_replace), all of the returned (groups) were placed into $variables.
True of Perl, but not PHP. "$1" isn't a valid PHP variable name; PHP variable names must start with an underscore or a letter. Backreferences of the form "$n" are only supported in regular expressions and replacement strings.
 
Top