views:

42

answers:

2

I have a string value from a user input box. I have to figure out if last char is a enter key (line feed).

Thats the code. Here I am checking if last char has a whitespace. Now I also have to check if last char is enter key (carriage return or line feed). How can i do this?

var txt = $get("<%= txtUserText.ClientID %>");
if (txt.value.substring(txt.value.length -1) !== ' ' || <checkifLastCharIsEnterKey>) 
  //my code to take action

**I don't think i need a keypress or keyup event because this above piece of code is not invoked at the time of user input.

+2  A: 

Well you could use a regular expression:

if (/[\r\n]$/.test(txt)) { /* it has a newline at the end */ }

If you want to get rid of it:

txt = txt.replace(/[\r\n]$/, '');

If you want to get rid of all "whitespace" at the end of the string:

txt = txt.replace(/\s*$/, '');
Pointy
Sorry man...it didn't work for me with square bracket...
Novice
+1  A: 

You can use a regular expression:

if(/\s$/.test(txt.value))

This will check whether the last character is any whitespace character (including the tab and newline characters).

EDIT:

To check for newlines separately:

if(/\r|\n$/.test(txt.value)) {
    //Newline
} else if(/\s$/.test(txt.value)) {
    //Any other whitespace character
}
SLaks
actually, i need to check whitespace and newline char separately. If Whitespace true Do thisIf newline true Do this
Novice
Then you can check whether the last character is equal to `'\r'` or `'\n'`. You can use the `charAt` method.
SLaks
@SLaks. Its working in both browsers FF and IE8 (in compatibility view mode). But there is one prob in IE8 browser...hit enter..code it trapping it... you hit whitespace code it getting it...but if you hit enter and give a whitespace as well.....newline condition is true (which is fine)...but it does not come back... what i mean is now after that whatever char you enter in input box... this newline condition remains true :(. Its only happening in IE8. ANy clue?
Novice
I have no idea what you mean.
SLaks
THanks anyways.
Novice