How to compare if string has a enter key in the end using jquery/javascript?
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>)
开发者_StackOverflow社区 //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.**
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
}
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*$/, '');
精彩评论