最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Check for Enter value in string - Stack Overflow

programmeradmin1浏览0评论

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")

发布评论

评论列表(0)

  1. 暂无评论