javascript - Check for Enter value in string - Stack Overflow

I have a string that is = textarea.valuevar str = "onetwothree"If I loop through the string

I have a string that is = textarea.value

var str = "one
two
three"

If I loop through the string, what is the value of the Enter key?

for (i = 0; i < str.length; i++) {
  if (str[i] === '????') {   
    console.log('found enter key')
  };
};

note: I know how to check when the enter key is pressed inside the textarea, I would like to check for it using the string.

I have a string that is = textarea.value

var str = "one
two
three"

If I loop through the string, what is the value of the Enter key?

for (i = 0; i < str.length; i++) {
  if (str[i] === '????') {   
    console.log('found enter key')
  };
};

note: I know how to check when the enter key is pressed inside the textarea, I would like to check for it using the string.

Share Improve this question asked Jul 11, 2017 at 4:11 w3mew3me 631 silver badge5 bronze badges 2
  • You mean a newline? – Andrew Li Commented Jul 11, 2017 at 4:12
  • It's called a line break. "Enter" is the name of the key. – Bergi Commented Jul 11, 2017 at 4:50
Add a ment  | 

3 Answers 3

Reset to default 1

Maybe search for \n\ or \r (or even \r\n):

var str = document.getElementById('text').value;
for (i = 0; i < str.length; i++) {
  if (str[i] === '\n' || str[i] === '\r') {
    console.log('found enter key')
  };
};
<textarea id="text"> "one
two
three"</textarea>

You should try '\n' if you want to check for new lines. Since pressing Enter, it creates a new line, I think this is what you are looking for

In Windows, the "enter" key is actually two characters. carriage return '\r' and line feed or newline '\n'. You could loop and check for just line feed/newline or check in pairs:

for (i = 0; i < str.length - 1; i++) {
  if (str[i] === '\r' && str[i + 1] === '\n') {   
    console.log('found enter key at pos ' + i + ' and ' + (i + 1))
  };
};

Additionally you could just use string.indexOf(searchValue,startPos)

str.indexOf("\r\n")

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745394042a4625797.html

相关推荐

  • javascript - Check for Enter value in string - Stack Overflow

    I have a string that is = textarea.valuevar str = "onetwothree"If I loop through the string

    9小时前
    10

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信