简体   繁体   中英

Ignore \n in javascript string

i have a basic system to convert \\n to <br/> but when i add Hello\\nhow are you in the box from a variable, \\n not is show, and this not have effect, only works when the user add \\n in the textarea to show in preview box. how can ignore \\n in js vars?

function convertirDialogo(val_, type) {
    val_ = val_.replace(/\\t/g, "<p class=\"create_t\"></p>");

    console.log(type);
    if (type !== 'DIALOG_STYLE_LIST') {
        val_ = val_.replace(/\\n/g, "<br />");
    }

    for (var i = 0; i < val_.length; i++) {
        var _list_created = false;
        if (type === 'DIALOG_STYLE_LIST') {
            var l_ = val_.charAt(i) == "\\" && val_.charAt(i + 1) == "n";
            if (i == 0 && l_ == false) {
                val_ = '<li>' + val_;
            } else {
                if (l_) {
                    val_ = val_.replace(/\\n/g, '<li>');
                }
            }
        }
        var start = i;
        var end = i + 7
        if (val_.charAt(start) == '{' && val_.charAt(end) == '}') {
            var _col = val_.substring(start, end + 1);
            var __col = _col.substring(1, _col.length - 1);

            val_ = val_.replace(_col, "<span style=\"color: #" + __col + ";\">");
        }
    }
    return val_;
}

example: http://image.prntscr.com/image/3312c7182fdf4e1d8a538c941c86bdf7.png

that works, but if i add button to add \\n to textbox from js not works.

当您可以简单地添加whitespace: pre-wrap时,这似乎需要做很多工作whitespace: pre-wrap在要显示字符串的位置处,将CSS规则whitespace: pre-wrap行。

I wrote the following html to help you understand what happens. In the example below, var a is two words separated by a new line character. Var b has all of the new lines replaced by xyzzy surrounded by spaces. Var c has all of the new lines replaced by
.

If you just write the strings into the document, <br /> is recognized in both reformatted and non-reformatted text. In non-formatted task, the new line is converted to a space and doesn't appear. However, in formatted text, the new line does cause a new line since spacing and line breaks are preserved.

Now we go to the input box of type text. The new line is a non-printing character and doesn't show up. The <br /> is just viewed as another piece of text and does not undergo special processing.

Next we go to the texture element. This element doesn't process HTML options, so the <br /> is just viewed as another piece of text. However, the new line character is used to represent a line break in the textarea element.

If you want to remove the new line characters, just replace them with an empty string in the same way that it was replaced by <br />. You can't really ignore the new line characters. You just have to realize how they are processed by the various elements.

 <!DOCTYPE html> <html> <head> <meta encoding="UTF-8" /> <title>Javascript replace function</title> <script> var a = "first\\nsecond"; var b = a.replace(/\\n/, " xyzzy "); var c = a.replace(/\\n/, "<br />"); </script> </head> <body> <p>This is a statement to study the Javascript replace function with new line characters</p> <ul> <li>Value a is the string first\\nsecond (\\n is a new line character)</li> <li>Value b has all of the new lines replaced by xyzzy surrounded by spaces</li> <li>Value c has all of the new lines replaced by &lt;br /&gt;</li> </ul> <script> var a; var b; var c; function starter() { var text1 = document.getElementById("text1"); var area1 = document.getElementById("area1"); var text2 = document.getElementById("text2"); var area2 = document.getElementById("area2"); var text3 = document.getElementById("text3"); var area3 = document.getElementById("area3"); text1.value = a; area1.value = a; text2.value = b; area2.value = b; text3.value = c; area3.value = c; } function list() { document.writeln("<li>Value a " + a + "</li>"); document.writeln("<li>Value b " + b + "</li>"); document.writeln("<li>Value c " + c + " </li>"); } window.onload = starter; </script> <p>Using Javscript to display variables</p> <ul> <script> list(); </script> </ul> <p>Working with preformatted text</p> <pre><ul> <script> list(); </script> </ul></pre> <form> <p>A <input type = "text1" id = "text1" /></p> <p>A <textarea id="area1"></textarea> </p> <p>B <input type = "text" id = "text2" /></p> <p>B <textarea id="area2"></textarea> </p> <p>C <input type = "text" id = "text3" /></p> <p>C <textarea id="area3"></textarea> </p> </form> <script> var test1 = /\\n/; document.writeln("<li>A " + test1.test(a) + "</li>"); document.writeln("<li>B " + test1.test(b) + "</li>"); document.writeln("<li>C " + test1.test(c) + "</li>");</script> </body> </html> 

When you have \\n in a JavaScript string literal, it represents a newline character, not a backslash followed by n . If you want a backslash followed by n , you have to escape the backslash character with another backslash character. That is, you have to put \\\\n in the string literal.

You can use the following code to place \\n in the textarea when the user presses the Enter key:

$(document).ready(function() {
  function replaceTextareaSelection(textarea, replacement) {
    var text = textarea.value,
      selectionStart = textarea.selectionStart,
      selectionEnd = textarea.selectionEnd;
    textarea.value = text.slice(0, selectionStart) + replacement + text.slice(selectionEnd);
    var selectionIndex = selectionStart + replacement.length;
    textarea.setSelectionRange(selectionIndex, selectionIndex);
  }

  $('#textlabel-input').keydown(function(e) {
    if (e.which == 13) {
      e.preventDefault();
      replaceTextareaSelection(this, '\\n');
    }
  });
});

jsfiddle

This also handles the case where the user has selected text in the textarea and presses the Enter key. To test this, enter abcdefghi in the textarea in the jsfiddle and select def . Then press the Enter key. The value of the textarea will change to abc\\nghi , and the caret will be just after the n .

I would use a regex on the string to achieve this:

 var patt1 = /\n/g;
 str.replace(patt1, '<br/>');

It will replace all newline delimiters.

Here in a jsfiddle Using a text area element

Read more here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM