Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I replace a match only at a certain position inside the string?

So, I have a function which has two params: string and match index to replace and i need to replace only match with that index. How can i do that?

Example:

replace('a_a_a_a_a', 1)

Result:

a__a_a_a
like image 303
ruslan.savenok Avatar asked Jul 27 '11 11:07

ruslan.savenok


People also ask

How do you replace a specific position in a string in python?

replace() method helps to replace the occurrence of the given old character with the new character or substring. The method contains the parameters like old(a character that you wish to replace), new(a new character you would like to replace with), and count(a number of times you want to replace the character).

How do you replace part of a string in HTML?

The replace() method searches a string for a value or a regular expression. The replace() method returns a new string with the value(s) replaced. The replace() method does not change the original string.

How do you replace a pattern in a string?

replace() The replace() method returns a new string with one, some, or all matches of a pattern replaced by a replacement . The pattern can be a string or a RegExp , and the replacement can be a string or a function called for each match. If pattern is a string, only the first occurrence will be replaced.

How do you replace a single character in a string JavaScript?

Answer: Use the JavaScript replace() method 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

Could look like:

var mystr = 'a_a_a_a_a';

function replaceIndex(string, at, repl) {
   return string.replace(/\S/g, function(match, i) {
        if( i === at ) return repl;

        return match;
    });
}

replaceIndex(mystr, 2, '_');

The above code makes usage of the fact, that .replace() can take a funarg (functional argument) as second parameter. That callback is passed in the current match of the matched regexp pattern and the index from that match (along with some others which we are not interested in here). Now that is all information we need to accomplish your desired result. We write a little function wish takes three arguments:

  • the string to modify
  • the index we wish to change
  • the replacement character for that position
like image 81
jAndy Avatar answered Oct 25 '22 05:10

jAndy