Search code examples
javascriptfunctionreplaceline-breaks

Replace new line with space in variable Javascript before function


I have the following code snipplet:

<script>
    var textstring = 
    'Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. 
Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.';

function insertNewLines(textstr, nos) {

var resulttext = '';
textstr = textstr.replace("\n", "<br />");
while (textstr.length > 0) {

resulttext += textstr.substring(0, nos) + '<br/>';
textstr = textstr.substring(nos);

}

The text in textstring is 2 rows i.e. there is a \r\n seperating the first from the second row. When I call the function it gives me an error even before I get the the replace part. (Debugger says that the block is not closed correctly because of the line break)

Is there a way I can get around that? I just need to get rid of the linebreak or even better keep it but let the script run correctly.

Thanks for all your help.

TheVagabond


Solution

  • There are two basic syntax errors in that code:

    1. You cannot have a newline in a string literal unless you escape it with a backslash. (You can in an ES2015 template literal, but not a string literal.) If you do, the newline is not included in the string. Use \r\n instead.

    2. You're missing the closing } on the function

    Aside from that, though, there's no need for the loop; JavaScript's replace can accept a regular expression with the g flag (for "global"), so:

    var textstring =
        'Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa.\r\nCum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.';
    
    function insertNewLines(textstr, nos) {
        return textstr.replace(/\r\n/g, "<br />");
    }
    
    console.log(insertNewLines(textstring));

    I've replaced the literal newline with a \r\n, and then replaced the loop with the single call to replace.