I am trying to manipulate a text where there are return (Enter) keys pressed. I mean:
"Hey man, how are you?
Here there is one enter above. And pressing 2 enters below.
Ok?"
The manipulated text should look like this: "Hey man, how are you?XHere there is one enter above. And pressing 2 enters below.XXOk?"
I want to detect where those return keys are pressed from a plain text like above, and put a char (i.e "X") at the place of these positions. Maybe detecting "n" chars where they can be visible? How can this be achieved in js?
2
Answers
On Windows and Mac a line break is a Carriage Return followed by a Line Feed (
rn
), on Linux it’s only a Line Feed (n
). Replacing both of them is easiest usingreplace
with a regular expression. Note that using backticks enables multiline string expressions, in order to mimic your scenario. Usingrn
andn
in the message has the same result.Simply use a regex replace. I used
/n/g
to define a regex which will match all newline characters (we can represent a newline character, in regex, usingn
). Then I usedreplace(/n/g, 'X')
, which says "replace all matches of the regex with'X'
.Note that when you run the following code snippet, the
OUTPUT TEXT
may appear to wrap onto multiple lines, but the output text does not contain any newline characters.