我如何插入或删除标签之前/之后的每一个新的行与Javascript字符串

How can I insert or remove a tab before / after every new line in a string with Javascript?

本文关键字:每一个 之后 字符串 Javascript 何插入 插入 标签 删除      更新时间:2023-09-26

考虑以下字符串,作为文本区的选择:

"我想在这个选区的每个换行符之后插入一个制表符。我还想知道如何做相反的事情,在此选择中删除每个换行符之前的制表符。"

和相关代码的简化示例:

var userWantsToIndentSelection = true,
userWantsToOutdentSelection = false,
start = this.selectionStart,
end = this.selectionEnd,
selection = text.slice(start,end),
newline = /'r|'n/.exec(selection);
if(newline){
    if (userWantsToIndentSelection){
        // add tabs after each newline
    }
    else if (userWantsToOutdentSelection) {
        // remove tabs before each newline
    }
}
if(!newline){
    // Handling just one line (cursor at front of line, no selection) is simple.
    // Perhaps I don't need a special handler though
    // and can use the new line handler for single and multiple line selections.
    // Mention it in your answer if you like.
}

我如何在Javascript字符串中的每个新行之前/之后插入或删除制表符?

你可以使用这个正则表达式src.replace(/^/gm, "'t");

^匹配行

的开头

m告诉regex引擎使用多行模式,以便^将匹配每一行,而不仅仅是字符串的开始。