Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript using .replace() at a specific index of the search

Tags:

javascript

Is there a function that can replace a string within a string once at a specific index of the string? Example:

var string1="my text is my text and my big text";
var string2="my";
string1.replaceAt(string2,"your",2);

and the resultant output would be "my text is my text and your big text"

like image 797
it freelance Avatar asked Oct 20 '18 15:10

it freelance


People also ask

How do you replace a string in a specific index?

The first method is by using the substr() method. And in the second method, we will convert the string to an array and replace the character at the index. Both methods are described below: Using the substr() method: The substr() method is used to extract a sub-string from a given starting index to another index.

What does the replace () method do?

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

How do you replace a letter in a string JavaScript?

You can use the JavaScript replace() method to replace the occurrence of any character in a string. However, the replace() will only replace the first occurrence of the specified character. To replace all the occurrence you can use the global ( g ) modifier.


1 Answers

You can do this with a little bit of manipulation, not requiring any regex.

I used this function to fetch the position (index) of another string within a string.

From there, it's as simple as returning a substring from the beginning to the found index, injecting your replacement, and then returning the rest of the string.

function replaceAt(s, subString, replacement, index) {
  const p = s.split(subString, index+1).join(subString);
  return p.length < s.length ? p + replacement + s.slice(p.length + subString.length) : s;
}

console.log(replaceAt("my text is my text and my big text", "my", "your", 2))
console.log(replaceAt("my text is my text and that's all", "my", "your", 2))
console.log(replaceAt("my text is my my my my text", "my", "your", 2))
like image 131
ugh StackExchange Avatar answered Sep 23 '22 20:09

ugh StackExchange