如何替换特定范围的索引? [英] How to replace at the particular range of indexes?

查看:132
本文介绍了如何替换特定范围的索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的字符串:

I have a string like this:

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

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

Now I want to append 4 spaces before every lines which are between this range: [14 - 40]. So I want this output:

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

换句话说,我想仅在特定范围内应用此替换:

In other word, I want to apply this replace just for a specific range:

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

但是,正如您所知,上面的代码将所有字符串替换为该正则表达式,那么,如何将其限制为仅用于特定位置?

But as you know, the above code replaces that regex for all of that string, Well, how can I limit it for just specific positions?

推荐答案

您可以将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之间发生替换.

Regex ^([\s\S]{13})([\s\S]{27}) makes sure replacement happens between position 14-40 only.

这篇关于如何替换特定范围的索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆