替换在给定偏移量之后出现的子字符串 [英] 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: <replaced>, Some other text'
显然,这样做的方法是将字符串 68
替换为字符串
.
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);
但是如果 User ID
包含相同的数字序列,这可能会在我的脸上爆炸.
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);
如您所见,现在我需要调用 substring
两次才能获得结果.但是有没有更简单的代码可以用来替换在给定偏移量之后出现的子字符串?
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);
这篇关于替换在给定偏移量之后出现的子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!