JavaScript string with new line - but not using \n

前端 未结 8 2015
故里飘歌
故里飘歌 2020-11-27 05:44

I have a string that has new lines in. I am wanting to convert these to HTML
s, but I\'m having a hard time detecting them.

Imagine a JavaScri

相关标签:
8条回答
  • 2020-11-27 05:52

    I don't think you understand how \n works. The resulting string still just contains a byte with value 10. This is represented in javascript source code with \n.

    The code snippet you posted doesn't actually work, but if it did, the newline would be equivalent to \n, unless it's a windows-style newline, in which case it would be \r\n. (but even that the replace would still work).

    0 讨论(0)
  • 2020-11-27 05:55

    Check for \n or \r or \r\n.

    There are several representations of newlines, see http://en.wikipedia.org/wiki/Newline#Representations

    0 讨论(0)
  • 2020-11-27 06:01

    This is a small adition to @Andrew Dunn's post above

    Combining the 2 is possible to generate readable JS and matching output

     var foo = "Bob\n\
        is\n\
        cool.\n\";
    
    0 讨论(0)
  • 2020-11-27 06:04

    UPDATE: I just came across a wonderful syntax design in JavaScript-ES6 called Template literals. What you want to do can be literally be done using ` (backtick or grave accent character).

    var foo = `Bob
    is
    cool`;
    

    In which case, foo === "Bob\nis\ncool" is true.

    Why the designers decided that ` ... ` can be left unterminated, but the " ... " and ' ... ' are illegal to have newline characters in them is beyond me.

    Just be sure that the targeting browser supports ES6-specified Javascript implementation.

     


    P. S. This syntax has a pretty cool feature that is similar to PHP and many more scripting languages, namely "Tagged template literals" in which you can have a string like this:

    var a = 'Hello', b = 'World';
    console.log(`The computer says ${ a.toUpperCase() }, ${b}!`);
    // Prints "The computer says HELLO, World!"
    
    0 讨论(0)
  • 2020-11-27 06:08

    The query string that I used to to escape the new line character in JS : LOAD DATA LOCAL INFILE 'Data.csv' INTO TABLE DEMO FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\r\n' IGNORE 1 ROWS;

    This involves new ES6 syntax - Template Literals `` and I tried changing '\n' to '\r\n' and worked perfectly in my case.

    PS: This example is my query to upload CSV data into mysql DB.

    0 讨论(0)
  • 2020-11-27 06:09

    I think they using \n anyway even couse it not visible, or maybe they using \r. So just replace \n or \r with <br/>

    0 讨论(0)
提交回复
热议问题