[英]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.
我在这里检查最后一个char是否有空格。 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.** ****我认为我不需要按键或键盘事件,因为在用户输入时不会调用上面的代码。**
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*$/, '');
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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.