在特定索引处插入字符串 [英] Insert a string at a specific index

查看:104
本文介绍了在特定索引处插入字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在另一个字符串的特定索引处插入字符串?

How can I insert a string at a specific index of another string?

 var txt1 = "foo baz"

假设我想在foo之后插入bar我该如何实现?

Suppose I want to insert "bar " after the "foo" how can I achieve that?

我想到了 substring(),但必须有一个更简单更简单的方法。

I thought of substring(), but there must be a simpler more straight forward way.

推荐答案

您可以将自己的 splice()原型化为String。

You could prototype your own splice() into String.

if (!String.prototype.splice) {
    /**
     * {JSDoc}
     *
     * The splice() method changes the content of a string by removing a range of
     * characters and/or adding new characters.
     *
     * @this {String}
     * @param {number} start Index at which to start changing the string.
     * @param {number} delCount An integer indicating the number of old chars to remove.
     * @param {string} newSubStr The String that is spliced in.
     * @return {string} A new string with the spliced substring.
     */
    String.prototype.splice = function(start, delCount, newSubStr) {
        return this.slice(0, start) + newSubStr + this.slice(start + Math.abs(delCount));
    };
}



示例



Example

String.prototype.splice = function(idx, rem, str) {
    return this.slice(0, idx) + str + this.slice(idx + Math.abs(rem));
};

var result = "foo baz".splice(4, 0, "bar ");

document.body.innerHTML = result; // "foo bar baz"

编辑:修改它以确保 rem 是绝对值。

Modified it to ensure that rem is an absolute value.

这篇关于在特定索引处插入字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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