0

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
  • Something like "<your string>".replaceAll("\n", "X\n")) ? Commented Oct 27, 2024 at 14:18
  • @Mike Yes, but how? I cannot acquire the string with "\n" chars Commented Oct 27, 2024 at 14:19

2 Answers 2

1

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, using \n). Then I used replace(/\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.

const text = ` Hey man, how are you? Here there is one enter above. And pressing 2 enters below. Ok? `.trim(); console.log('INPUT TEXT:'); console.log(text); console.log('\n'); console.log('OUTPUT TEXT:'); console.log(text.replace(/\n/g, 'X')); console.log('\n');

Sign up to request clarification or add additional context in comments.

Comments

1

On Windows and Mac a line break is a Carriage Return followed by a Line Feed (\r\n), on Linux it's only a Line Feed (\n). Replacing both of them is easiest using replace with a regular expression. Note that using backticks enables multiline string expressions, in order to mimic your scenario. Using \r\n and \n in the message has the same result.

const message = `This text contains several line breaks`; const lineBreakReplacement = "X"; const messageWithLineBreaksReplaced = message.replace(/\r\n|\n/g, lineBreakReplacement ); console.log(messageWithLineBreaksReplaced); // This textX contains severalX line breaks 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.