首页 > 解决方案 > 为什么 '\n' 不适用于 ServiceNow 脚本?未创建新行

问题描述

我们已经尝试了几种变体'\n'并尝试过'\r',但脚本不断将这些行一起返回或在它们之间有空格,而不是作为实际的新行。这是底部两个问题的脚本:

(function(current, previous, gs, action) {
    var eqStr ='cmdb_ci=' + current.getValue('cmdb_ci');

//eqStr='short_description=' + current.getValue('short_description');
    //eqStr += '^description=' + current.getValue('description');

    eqStr +='^priority=' + current.getValue('priority');
    eqStr +='^sys_domain=' + current.getValue('sys_domain');
    eqStr +='^company=' + current.getValue('company');
    eqStr +='^justification=' + current.getValue('number')
        + '\n' + current.getValue('short_description')
        + '\n' + current.getValue('description') ;

标签: javascriptservicenow

解决方案


如果您要构建的字符串最终将被注入到 DOM 元素中,则必须使用负责解析 DOM 元素的 HTML 解析器熟悉的代码。HTML 解析器不知道 JavaScript 字符串转义码,如下所示:

let output = "This is\na test.";
document.querySelector("div").innerHTML = output;

let output2 = "This is\nanother test.";
document.querySelector("p").textContent = output2;
<div></div>
<p></p>

对于将成为 DOM 元素的一部分的字符串,您需要使用创建换行符的 HTML 标签<br>

let output = "This is<br>a test.";
// innerHTML invokes the parser to parse the supplied string:
document.querySelector("div").innerHTML = output;

let output2 = "This is<br>another test.";
// This won't produce the line break because textContent doesn't invoke the HTML
// parser. Insted, the actual text will be placed in the string.
document.querySelector("p").textContent = output2; 
<div></div>
<p></p>


推荐阅读