Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I replace a string by range?

I need to replace a string by range Example:

string = "this is a string";//I need to replace index 0 to 3 whith another string Ex.:"that"
result = "that is a string";

but this need to be dinamically. Cant be replace a fixed word ...need be by range

I have tried

           result = string.replaceAt(0, 'that');

but this replace only the first character and I want the first to third

like image 383
DevMobile Avatar asked Sep 24 '12 15:09

DevMobile


People also ask

How do I replace a string without replacing it?

To replace a character in a String, without using the replace() method, try the below logic. Let's say the following is our string. int pos = 7; char rep = 'p'; String res = str. substring(0, pos) + rep + str.

Can we replace a string?

Java String replace() MethodThe replace() method searches a string for a specified character, and returns a new string where the specified character(s) are replaced.


2 Answers

function replaceRange(s, start, end, substitute) {
    return s.substring(0, start) + substitute + s.substring(end);
}

var str = "this is a string";
var newString = replaceRange(str, 0, 4, "that"); // "that is a string"
like image 195
Alexander Pavlov Avatar answered Sep 21 '22 05:09

Alexander Pavlov


var str = "this is a string";
var newString = str.substr(3,str.length);
var result = 'that'+newString

substr returns a part of a string, with my exemple, it starts at character 3 up to str.length to have the last character...

To replace the middle of a string, the same logic can be used...

var str = "this is a string";
var firstPart = str.substr(0,7); // "this is "
var lastPart = str.substr(8,str.length); // " string"
var result = firstPart+'another'+lastPart; // "this is another string"
like image 29
Salketer Avatar answered Sep 20 '22 05:09

Salketer