skip to Main Content

I have a HTML textinput, which I store into a string. I then perform changes to the string and print the result out in a div block next to the input field. However, user input marks newlines as "n", and innerHTML marks newlines as "<br>". The methods of converting one into the other I tried so far didn’t work.

Method 1:
During the transforming process I temporarily perform s = s.split('');, then iterate through the whole string to perform changes. I tried doing if (s[i] == 'n') s[i] = '<br>', but it didn’t detect the newlines.

Method 2:
After joining the string back, I tried to use RegEx: s = s.replace("/n/g", "<br>". The result was the same – it didn’t detect the newlines.

This code shows my problem:

let test = "danda"
console.log(test);
test = test.replace("/n/g", "<br>");
console.log(test);

Expected output:

da
da
da<br>da

Actual output:

da
da
da
da

2

Answers


  1. A single solution for this case

    test = test.replace(/n/g, "<br>");
    
    // using replaceAll
    test = test.replaceAll("n", "<br>");
    
    Login or Signup to reply.
  2. "danda".replace(/n/g, "<br>")
    

    Remove the quotes from your regex.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search