[英]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.