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
3 Answers
Reset to default 1Maybe 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")