Skip to content Skip to sidebar Skip to footer

Replace A Substring That Occurs After A Give 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:

Solution 1:

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);

Solution 2:

Can you count on the delimiters and the location of the text you want to replace in relation to the delimiters? If so, here's couple methods of replacing text spliting and spliceing on delimiters.

Simpler one, split on comma, replace second element in its entirety:

JSFiddle

var str = 'User ID: 2894, Task ID: 68, Some other text'
arr1 = str.split(', ')
arr1.splice(1, 1, 'Task ID: <replaced>')
str = arr1.join(', ')
console.log(str)

A little more complex, first split on comma, then colon:

JSFiddle

var str = 'User ID: 2894, Task ID: 68, Some other text'
arr1 = str.split(', ')
arr2 = arr1[1].split(': ')
arr2.splice(1, 1, '<replaced>')
arr1[1] = arr2.join(': ')
str = arr1.join(', ')
console.log(str)

Simply an alternative to replace. I think the replace option is better for the case you presented.

Solution 3:

Alternate answer. Less error prone. It would certainly be easier to work with this string if it were JSON.

var targetId = '68';

var str = 'User ID: 2894, Task ID: 68, Some other text';
var items = str.split(', ');
var prefix = 'Task ID: ';

var foundIndex = items.indexOf(prefix + targetId);
if(foundIndex > -1){
    items.splice(foundIndex, 1, prefix + '<replaced>');
}
var newStr = items.join(', ');
alert(newStr);

Post a Comment for "Replace A Substring That Occurs After A Give Offset"