gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 08:08:55 28 4
gpt4 key购买 nike

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

"I want to insert \n a tab after every newline in the this selection. \n I also want to know how to do the opposite, removing the tab before each newline in this selection."

以及所涉及代码的简化示例:

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 告诉正则表达式引擎使用多行模式,以便 ^ 将匹配每一行,而不仅仅是字符串的开头。

关于javascript - 如何使用 Javascript 在字符串中的每个新行之前/之后插入或删除制表符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24498570/

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