【问题标题】:How to replace at the particular range of indexes?如何在特定的索引范围内替换?
【发布时间】:2016-01-27 06:40:16
【问题描述】:

我有一个这样的字符串:

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

现在我想在此范围之间的每一行之前附加 4 个空格:[14 - 40]。所以我想要这个输出

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

换句话说,我想将此替换应用于特定范围:

var output = str.replace(/^(.*)$/gm, "    $1");

但是如你所知,上面的代码替换了所有字符串的正则表达式,那么,我怎样才能将它限制在特定的位置?

【问题讨论】:

  • Range 14-40?这些是像test14 - test40 还是它们是索引值。
  • @Rajesh 不,它们只是索引值。
  • 所以不应该是数组吗?
  • 切片+连接; left+mid.replace+right
  • @Rajesh 没有任何数组,只有一个字符串,我想要一个字符串作为输出。

标签: javascript jquery regex


【解决方案1】:

您可以将replacecallback 一起使用:

var str = "this is test1\n"+
           "this is test2\n"+
           "this is test3\n"+
           "this is test4";

var posStart = 14; // start index
var posEnd   = 40; // end index
var re = new RegExp(
  '^([\\s\\S]{' + (posStart-1) + '})([\\s\\S]{' + (posEnd-posStart+1) + '})');
//=> re = /^([\s\S]{13})([\s\S]{27})/

var r = str.replace(re, function($0, $1, $2) {
    return $1+$2.replace(/\n/g, '\n    '); });

console.log(r);
/* 
"this is test1
    this is test2
    this is test3
this is test4"
*/

正则表达式 ^([\s\S]{13})([\s\S]{27}) 确保仅在位置 14-40 之间发生替换。

【讨论】:

  • OP 写道:我想追加 4 个空格
  • 非常好 +1 .. 谢谢。但有一件事,你的正则表达式中的这些数字来自哪里? (13, 27) 我的意思是你如何计算它们?
  • 这是由于您要求仅替换输入中的位置14-40。所以目标之前的13 字符是$1,然后14-40 使其成为下一个27
  • 我的最后一个问题是,如何在正则表达式中使用变量而不是那些数字? (13, 27)
  • 让我相应地修改答案
【解决方案2】:

你可以试试这样的:

另外请注意,它不是检查 char 逻辑索引的好选择。

function addSpaces(){
  var str = "this is test1\n"+
            "this is test2\n"+
            "this is test3\n"+
            "this is test4"
  var data = str.split("\n");
  
  var result = data.map(function(item, index){
    if(index >0 && index < data.length-1){
      item = "    " + item;
    }
    return item;
  }).join("\n");
  
  console.log(result)
}

addSpaces();

【讨论】:

  • :-) 谢谢.. 但是看,只有 4 行.. 正如您在示例中看到的那样。我需要在第二行和第三行 (或此范围 [14 - 40])之前添加 4 个空格 (或应用该正则表达式)
  • @stack 我将删除我的答案。但请解释您的问题陈述。另外,范围是指字符索引吗?
  • 好的,请看这个:t(0)h(1)i(2)s(3) (4)i(5)s(6) (7)t(8)e(9)s(10)t(11)1(12) ...,看到了吗?每个字符都有一个数字。现在我想在这个范围内应用这个正则表达式:[14 - 40]1440 是位置的数字。
  • 所以换个说法,对于范围 14-40,在每个换行符之后,您要添加 4 个空格。对吗?
  • @stack 我已经根据我对问题的理解更新了我的答案。希望对你有帮助
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-09-14
  • 2018-05-02
  • 1970-01-01
  • 1970-01-01
  • 2016-05-31
  • 1970-01-01
  • 2016-07-30
相关资源
最近更新 更多