gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 02:14:19 24 4
gpt4 key购买 nike

假设我有一个像这样的输入字符串:

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 检测新行,但我需要在迭代字符串时进行检测。有没有办法在循环执行时检测新行?

最佳答案

是的,但是:

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];
}

带有转义的演示(注意它永远不会打印检测到新行!):

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];
}

关于javascript - 有没有办法在迭代字符串时检测新行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49563412/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com