简体   繁体   English

如何使用Javascript在字符串中的每个新行之前/之后插入或删除选项卡?

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

Consider the following string, as a selection in a textarea: 考虑以下字符串,作为文本区域中的选择:

"I want to insert \\na 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." “我想在此选择中的每个换行符之后插入\\ na选项卡。\\ n我也想知道如何做相反的事情,在此选择中的每个换行符之前删除选项卡。”

And a simplified example of the code involved: 以及所涉及代码的简化示例:

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.

}

How can I insert or remove a tab before / after every new line in a string with Javascript? 如何使用Javascript在字符串中的每个新行之前/之后插入或删除选项卡?

you can use this regex src.replace(/^/gm, "\\t"); 您可以使用此正则表达式src.replace(/^/gm, "\\t");

^ matches the start of line ^与行首匹配

The m tells the regex engine to use the multi-line mode so that ^ will match each line and not only the start of the string. m告诉正则表达式引擎使用多行模式,以便^将匹配每一行,而不仅是字符串的开头。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我可以使用javascript在每隔一行插入一些字符串吗? - Can I insert some string at every other line using javascript? 如何每隔五个单词用新行分解javascript字符串? - How can I break up a javascript string with a new line every five words? 如何在 javascript 中每 n 个字符后插入一个字符? - How can I insert a character after every n characters in javascript? 如何使用javascript删除字符串中指定单词之后和句点之前的所有字符? - How can I remove all characters after a specified word and before a period in a string using javascript? 如何在JavaScript中的字符串的每个新行中添加“>”? - How to add '>' to every new line in a string in javascript? 如何从javascript中的字符串中删除每个第n个字符? - How can I remove every nth character from a string in javascript? 如何使用JavaScript循环遍历长字符串以在每次匹配后插入新字符串 - How to use JavaScript to loop through a long string to insert a new string after every match 如何在JavaScript中的文本后插入新行 - How to insert a new line after a text in javascript 使用javascript / jQuery插入新行时,如何在每个表格行中插入“删除按钮” - How do I insert a “remove button” to every table row when inserting a new row using javascript/jQuery 在JavaScript数组初始化程序之后Eclipse可以用1个选项卡缩进新行吗? - Can Eclipse indent new line with 1 tab after JavaScript array initializer?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM