How To Replace At The Particular Range Of Indexes?
I have a string like this: var str = 'this is test1 this is test2 this is test3 this is test4'; Now I want to append 4 spaces before every lines w
Solution 1:
You can use replace
with 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"
*/
Regex ^([\s\S]{13})([\s\S]{27})
makes sure replacement happens between position 14-40
only.
Solution 2:
You can try something like this:
Also note, its not a good option to check for char index for logic.
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();
Post a Comment for "How To Replace At The Particular Range Of Indexes?"