2

Hi =) I have some code that I am struggling with. I have a function to replace specific html characters values like a tab or new line, however it doesn't seem to work very well.

var replaceHTMLCharacters = function(text){
  text = text.split("");
    for(var i = 0; i < text.length; i++){
        if(text[i].charCodeAt(0) == 10){
            text[i] = "\n";
        }
    }
  text = text.join("");
  console.log(text);
  return text;
}

This is an example of me trying to remove a new line character and replace it with "\n" so that I can store it in a JSON format. It reaches the point where it says text[i] = "\n" but then doesn't actually set this character to a "\n". Can anyone tell me what I am doing wrong? Thank you.

Pixelknight1398
  • 537
  • 2
  • 10
  • 33

5 Answers5

2

"\n" is a newline character. You're replacing them with what's already there, leaving the String unchanged. If you want the actual characters \ and n, you need to mask the backslash \\n and insert that.

0

I think you would be better off using a bit of regex here. Try this code (I also purposely renamed your function to have a bit more describing name):

function breakOnTab (string) {
    return string.replace(/\t/g, '\r\n')
}

This regex finds all tab characters \t and replaces them with a string consisting of escaped carriage return and new line.

Leo Napoleon
  • 969
  • 6
  • 11
0

It seems you are replacing "\n" with "\n". To replace '\n' you will need to escape it by adding an additional '\' or '\n'

Nick Satija
  • 181
  • 7
0

First of all: HTML chars do not exist...

Second: I don't understand why you did text = text.split("");, you will iterate over an array instead of an String, spending time and memory...

Third: '\n' charCode is 10...

If you want to rewrite text formatted on HTML to plain text, you could do something like:

var replaceHTMLCharacters = function(text){
  text = text.replace(/<br\s*\/?>/g,'\n');
  console.log(text);
  return text;
}
jdrake
  • 333
  • 4
  • 17
0

You could use something like this with \n and \t ..

You could check also checkout Difference between \n and \r?

var replaceHTMLCharacters = function(text) {
  var reg = new RegExp(/(\r\n?|\n|\t)/g);
  var ntext = text.replace(reg, "-");
  console.log(ntext);
  return text;
}

replaceHTMLCharacters(`newLine
Text1`)
replaceHTMLCharacters("Tab text2");
Community
  • 1
  • 1
Sreekanth
  • 3,110
  • 10
  • 22