如何替换两个索引之间的子字符串 [英] How to replace a substring between two indices

查看:120
本文介绍了如何替换两个索引之间的子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Javascript中的两个索引之间替换文本,例如:

I want to replace text between two indices in Javascript, something like:

str = "The Hello World Code!";
str.replaceBetween(4,9,"Hi");
// outputs "The Hi World Code"

索引和字符串都是动态的。

The indices and the string are both dynamic.

我怎么能这样做?

推荐答案

那里在JavaScript中没有这样的方法。但你可以随时创建自己的:

There is no such method in JavaScript. But you can always create your own:

String.prototype.replaceBetween = function(start, end, what) {
    return this.substring(0, start) + what + this.substring(end);
};

"The Hello World Code!".replaceBetween(4, 9, "Hi");
// >> "The Hi World Code!"

这篇关于如何替换两个索引之间的子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆