简体   繁体   English

如何使用jquery / javascript比较string是否最后有一个回车键?

[英]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.

相关问题 EntityType没有使用字符串作为键定义的键 - EntityType Has No Key Defined Using String as Key 如何比较具有动态值的字符串 - How to compare string which has dynamic value 在使用Javascript / C#在CKEditor中键入特定字符(例如Enter键或Esc键)时,如何显示警报消息? - How to show alert message while typing particular character like Enter key or Esc key in CKEditor using Javascript/C#? 我有一个开头相同但结尾总是一些随机数的响应,我想使用通配符进行比较,我该怎么做? - I have a response that has the same beginning but always some random number at the end, i want to compare using a wildcard, how can I do it? 需要输入转义键结束程序 - Need to enter escape key to end program 尝试使用ENTER键在gridview的最后一行中结束单元格的编辑 - Trying to end editing of cell while on the last row of a gridview using the ENTER key 通过Javascript,Jquery比较DateTime - Compare DateTime by Javascript, Jquery 比较字符串包含所有数字并比较日期 - compare string has all numbers and compare Date 如何在IReadOnlyCollection上将键/值字典与==运算符进行比较 <string> ? - How to compare key/value dictionary with == operator on a IReadOnlyCollection<string>? 如何将字符串与字典中的键值进行比较? - How do I compare a string with key value in dictionary?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM