我有一个具有以下格式的字符串:
'User ID: 2894, Task ID: 68, Some other text'
假设我需要将此字符串转换为以下内容:
'User ID: 2684, Task ID: <replaced>, Some other text'
显然,这样做的方法是替换字符串68
与字符串 <replaced>
.
var str = 'User ID: 2894, Task ID: 68, Some other text';
var newStr = str.replace('68', '<replaced>');
alert(newStr);
但是如果User ID
,这可能会在我脸上爆炸。包含相同的数字序列。
var str = 'User ID: 2684, Task ID: 68, Some other text';
var newStr = str.replace('68', '<replaced>');
alert(newStr);
但是,我还有有关应替换的子字符串的字符索引的信息。所以我有以下代码来完成此任务:
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
两次即可得到结果。但是是否有更简单的代码可以用来替换给定偏移量之后出现的子字符串?
最佳答案
将您的前缀添加到替换函数中。
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);
//编辑* 在这里也添加一个逗号后缀,以防存在其他以 68 开头的任务 ID 号。显然,这个答案假设您要替换的并不总是 68,并且无论数字是什么传递到这个函数中。
关于javascript - 替换给定偏移量之后出现的子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29549686/