如何在特定的索引范围内替换?

时间:2016-01-27 06:40:16

标签: javascript jquery regex

我有一个这样的字符串:

import {HeroService,SomeInterface} from './hello.service';

console.log('service = '+HeroService); // <---- not null
console.log('interface = '+SomeInterface); // <---- undefined

现在我想在此范围之间的每一行之前追加4个空格:var str = "this is test1 this is test2 this is test3 this is test4"; 。所以我想要输出

[14 - 40]

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

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

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

2 个答案:

答案 0 :(得分:1)

您可以尝试这样的事情:

另请注意,检查逻辑的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();

答案 1 :(得分:1)

您可以将 Warning: copy() [function.copy]: Filename cannot be empty in C:\Apache2.2\htdocs\account.php on line 3 replace

一起使用
callback

正则表达式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})之间进行替换。