Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript regex not matching last char in form

I have this simple regex to catch the last instance of 'turn to 123' in a form (I have another regex for the main body):

currenttext=currenttext.replace(/([^>])(turn\s+to\s+)(\d+)$/i,"$1<tt ref=\"$3\">$2$3</tt>");

which for example substitutes turn to 123... with

<tt ref="123">turn to 123</tt>...

...in live form input. However it only works if there is some form of character after the number 123, whether it be a carriage return or a visible character, which I cannot fathom since the $ end of match anchor clearly has no other character prior to the memory pattern for the numerical digits. Without a subsequent character I get this result:

<tt ref="12">turn to 12</tt>3

i.e. it fails to catch the last digit completely. I have tried putting the $ anchor inside the memory parens but made no difference.

like image 211
Beeblbrox Avatar asked Nov 05 '22 05:11

Beeblbrox


1 Answers

I am quite certain there is nothing wrong with this regex. You must be getting the wrong text as the input currenttext. You can verify this by checking currenttext before running this code (either console.log(currenttext) or alert(currenttext), or something like that).

Things to look out for:

  • Are you using substring(...) with (begin, end) instead of (begin, end+1)?
  • Are you matching the last character as a separate group in a RegExp?
like image 185
Raze Avatar answered Nov 07 '22 20:11

Raze