如何检测字符串中的特定范围是否在换行符中

How to detect whether a specific range from string is in the newline?

本文关键字:范围 范围是 是否 换行符 检测 字符串 何检测      更新时间:2023-09-26

我有一个这样的字符串:

var str = "this is test1
           this is test2
           this is test3";

现在我想要如果该范围的两边都'n则返回true,否则返回false。在上面的示例中,只有以下三个范围是正确的:

[0 - 12] => true

[14 - 26] => true

[27 - 39] => true

所有其他范围都必须false.像这些: [1 - 12][5 - 17] , ...


注意:该范围之前和之后的空格无关紧要。例如:

var str = "     this is a test    ";

现在这个范围是true[0 - 20][2 - 18][5 - 22],...


实际上,我正在

尝试创建一个降价编辑器,现在我正在研究其代码方法按钮。所以我需要知道,如果所有选定的文本(该范围)都在一行中,则在其前面附加 4 个空格,否则在它周围附加两个"'"。

尝试使用

onselect 事件,将输入文本的每一行存储在数组中,使用 RegExp 'n 检查每行是否有保存的变量。另请参阅获取当前选定的文本

var textarea = document.querySelector("textarea"), re = /'n/;
textarea.onselect = function(e) {
  var res = [];
  // current selection
  var sel = this.value.slice(this.selectionStart, this.selectionEnd);
  // create array of input value split at new line characters
  var matches = this.value.split(re);
  // split input value at new line characters
  // return `true` or `false`
  var selected = sel.split(re);
  for (var i = 0; i < selected.length; i++) {
    if (matches.indexOf(selected[i]) !== -1) {
      res.push(true)
    } else {
      res.push(false)
    }
  }
  console.log(matches, res, selected)
}
<textarea style="width:300px;height:200px">
  this is test1
  this is test2
  this is test3</textarea>