有没有办法在迭代字符串时检测新行?

时间:2018-03-29 19:08:08

标签: javascript typescript

假设我有一个输入字符串:

var str = "hello i am a
robot, have a 
nice day";

我正在迭代字符串:

let newTxt: string = "";
for (var i = 0; i < str.length; i++) {
    if (str[i] == "\n") {
        // i want something like that...
        console.log("new line detected!");
    }
    newTxt += str[i];
}

我知道可以使用Regex检测新行,但我需要在迭代字符串时进行检测。 有没有办法在循环执行时检测新行?

1 个答案:

答案 0 :(得分:2)

是的,但是:

var str = "hello i am a
robot, have a 
nice day";

语法无效。

逃避(不会创建'\n'):

var str = "hello i am a\
robot, have a \
nice day";

或使用模板字符串(确实创建'\n'):

var str = `hello i am a
robot, have a 
nice day`;

当然,如果您自己声明",也可以使用\n

var str = "hello i am a\nrobot, have a\nnice day";

否则您的代码正常

模板字符串演示(删除newTxt: string中的类型,以便您可以在此处运行):

&#13;
&#13;
var str = `hello i am a
robot, have a 
nice day`;

let newTxt = "";
for (var i = 0; i < str.length; i++) {
    if (str[i] == "\n") {
        // i want something like that...
        console.log("new line detected!");
    }
    newTxt += str[i];
}
&#13;
&#13;
&#13;

带有转义的演示(注意它永远不会打印new line detected!):

&#13;
&#13;
var str = `hello i am a\
robot, have a \
nice day`;

let newTxt = "";
for (var i = 0; i < str.length; i++) {
    if (str[i] == "\n") {
        // i want something like that...
        console.log("new line detected!");
    }
    newTxt += str[i];
}
&#13;
&#13;
&#13;