skip to Main Content

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


  1. 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 using replace with a regular expression. Note that using backticks enables multiline string expressions, in order to mimic your scenario. Using rn and n in the message has the same result.

    const message = `This text
    contains several
    line breaks`;
    const lineBreakReplacement = "X";
    const messageWithLineBreaksReplaced = message.replace(/rn|n/g, lineBreakReplacement );
    console.log(messageWithLineBreaksReplaced); // This textX    contains severalX    line breaks 
    
    Login or Signup to reply.
  2. 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');
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search