假设我有一个输入字符串:
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
检测新行,但我需要在迭代字符串时进行检测。
有没有办法在循环执行时检测新行?
答案 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
中的类型,以便您可以在此处运行):
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;
带有转义的演示(注意它永远不会打印new line detected!
):
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;