Search code examples
javascriptreplacesubstring

Replace a substring that occurs after a given offset


I have a string that has following format:

'User ID: 2894, Task ID: 68, Some other text'

Let's say I need to convert this string to the following:

'User ID: 2684, Task ID: <replaced>, Some other text'

Obviously, the way to do this is to replace string 68 with the string <replaced>.

var str = 'User ID: 2894, Task ID: 68, Some other text';
var newStr = str.replace('68', '<replaced>');
alert(newStr);

But this could blow up on my face if User ID contained the same sequence of numerals.

var str = 'User ID: 2684, Task ID: 68, Some other text';
var newStr = str.replace('68', '<replaced>');
alert(newStr);

However, I also have information about the character index of the substring that should be replaced. So I have following code to do this task:

var str = 'User ID: 2684, Task ID: 68, Some other text';
var taskId = '68';
var prefix = 'Task ID: ';
var index = str.indexOf(prefix) + prefix.length;
var newStr = str.substring(0, index) + '<replaced>' + str.substring(index + taskId.length);
alert(newStr);

As you can see, now I need to call substring twice to get the result. But is there a simpler code which I could use to replace a substring that occurs after a given offset?


Solution

  • Add your prefix to the replace function.

    var str = 'User ID: 2894, Task ID: 68, Some other text';
    var prefix = 'Task ID: ';
    var newStr = str.replace(prefix + '68' + ',', prefix + '<replaced>,');
    alert(newStr);
    

    // EDIT* Adding a comma suffix here too, in case there is some other Task ID number starting with 68. Obviously this answer assumes it won't always be a 68 that you're replacing, and whatever number will be passed into this function.