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?
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);
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 split
ing and splice
ing 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.
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);