Sometimes, we want to check whether a JavaScript string contains a line break.
In this article, we’ll look at how to check whether a JavaScript string contains a line break.
How to check whether a JavaScript string contains a line break?
To check whether a JavaScript string contains a line break, we can use the JavaScript regex’s exec
method.
For instance, we write:
const text = "abc\n123"
const match = /\r|\n/.exec(text);
console.log(match)
We call /\r|\n/.exec
with text
to return the matches of newline characters in text
.
As a result, we get ['\n', index: 3, input: 'abc\n123', groups: undefined]
Conclusion
To check whether a JavaScript string contains a line break, we can use the JavaScript regex’s exec
method.