tags:

views:

85

answers:

5

Hello,

I have an HTML page with a text box. This text box has an id of "myTextBox". I am trying to use a regular expression in JavaScript to replace certain values in the text box with another value. Currently, I am trying the following

function replaceContent()
{
  var tb = document.getElementById("myTextBox");
  if (tb != null)
  {
    var current = new String(tb.value);
    var pattern = new RegExp("(ft.)|(ft)|(foot)", "ig");
    current = current.replace(pattern, "'");
    alert(current);
  }
}

Based on this code, if I had the value "2ft" in the myTextBox, I would expect the current variable to be "2'". However, it always shows an empty string. I fear there is something that I am misunderstanding in relation to regular expressions in JavaScript. What am I doing wrong?

Thank you!

+2  A: 

Rewrite your pattern to:

(ft\.?|foot|feet)

This will match "ft" or "ft." and "foot" or "feet".

When writing code that uses regular expressions that won't behave, assume (first) that it is your regex that is the problem. Thanks to the compact and esoteric "programming" of regular expressions, it's quite easy to make a mistake you don't see.

If you test the following in Firebug to yield a correct result:

"2ft".replace(/(ft\.?|foot|feet)/ig, "'")

You will get "2'" in your console.

So this answer ought to solve your problem, if the regex is your problem in the first place. Like Rubens said, please check the ID of your textbox and ensure that the item is correctly retrieved.

The Wicked Flea
A: 

As The Wicked Flea says, the literal '.' in your regex needs to be escaped. If it's in a character class it can be written un-escaped, but outside of one it must be escaped.

Skilldrick
A: 

The following works for me:

<script>
var current = "2ft";
var pattern = new RegExp("(ft.)|(ft)|(foot)", "ig");
current = current.replace(pattern, "'");
alert(current);
</script>

Are you sure that tb.value is evaluating properly?

Eric
A: 

I ran your code using IE8,Chrome and FF3 with no problems.

Please check if your textbox id is correct.

Rubens Farias
A: 

The problem is that you're alternating explicit groupings. Instead you can just do something like the following:

function replaceContent()
{
  var tb = document.getElementById("myTextBox");
  if (tb != null) {
    current = tb.value.replace(/\s*(ft\.|ft|foot|feet)\b/ig, "'");
    alert(current);
  }
}

Also, note the \s* which will strip leading spaces and the \b which marks the beginning/end of a word. I also added feet.

Robert Mah