Closed Thread Icon

Preserved Topic: JS Regular Expression problem (Page 1 of 1) Pages that link to <a href="https://ozoneasylum.com/backlink?for=18343" title="Pages that link to Preserved Topic: JS Regular Expression problem (Page 1 of 1)" rel="nofollow" >Preserved Topic: JS Regular Expression problem <span class="small">(Page 1 of 1)</span>\

 
mobrul
Bipolar (III) Inmate

From:
Insane since: Aug 2000

posted posted 06-11-2002 20:18

I have this textarea, I need to have users enter text into.
I need to check for, among other things, 3 digit numbers, then replace them with <span class='red'>3 digit number</span>.
The first 3 digit number in the string converts fine, my problem comes with any 3 digit numbers that come later in the string (any past the 1st 3 digit number). My regular expression just seems to ignore them. I thought regular expressions change all instances of the sub-string, not just the first. Here is some code(newText is the string we are testing):

code:
//set regex
var reNum = /\d\d\d/;

//check for 3digit numbers

if (reNum.test(newText)){
Num = newText.match(reNum);
for(i=0; i<Num.length; i++){
var reNumNew = '/'+Num[i]+'/';
var NumPlus = ' <span class="red">'+Num[i]+'</span> ';
NewNumText = newText.replace(reNumNew,NumPlus);
newText = NewNumText;
}
}

//continue on to next test, similar to the 3 digit test



One of my big confusions is, if I put an alert in there, at the beginning of the for loop, that returns Num.length, it always returns '1', regardless of how many 3 digit numbers are in the string. 0 3 digit numbers or 100 3 digit numbers, always 1.

This has been making me crazy for a day and a half...I've tried every twist and turn and tactic I can think of to make this work and I simply can't.
I know it must be something simple...
Anybody with a new set of eyes want to help?

Thanks
mobrul

hlaford
Bipolar (III) Inmate

From: USA! USA! USA!
Insane since: Oct 2001

posted posted 06-11-2002 20:39

the regex you want is

code:
/\d{3}/g



the "g" tells it to keep going after the first match.

in fact, you could prolly do the whole thing in one line of code:

code:
oldString = oldString.replace(/(\d{3})/g, "<span class=\"red\">$1</span>");



as a separate item, i would recommend using a different class name, perhaps one that is more descriptive of the numbers rather than the style which is to be applied.



[This message has been edited by hlaford (edited 06-11-2002).]

mobrul
Bipolar (III) Inmate

From:
Insane since: Aug 2000

posted posted 06-11-2002 21:28

you are a genius!
Thank you for the help.
It turns out I had to use the $& instead of $1, but you certainly pointed me in the right direction. I was trying too hard...much easier way.
Thanks.
mobrul

« BackwardsOnwards »

Show Forum Drop Down Menu