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

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

最佳答案

是的,但是:

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/

相关文章:

javascript - 从 IBM Worklight Adapter 读取域

typescript - 网络 Storm "Warning:File was not compiled because there is no a reference from tsconfig.json"

typescript - 元素隐式具有 'any' 类型

typescript - 如何以可用的方式重新导出其中包含接口(interface)的导入模块?

javascript - 在 Svelte 中导入 Stencil

javascript - Angular 2 : Change detection inside observable

javascript - 从 JavaScript 文件加载变量时在文件名中使用今天的日期

javascript - 使用 Ember.js 捕获代码错误的更好实践(特别是困惑的变量名称)

javascript - 未使用传递给 Soundmanager 的选项(通过 Soundcloud JS SDK)

javascript - typescript 中的 ... 语法是什么