【问题标题】:Insert text in javascript textbox on correct position [duplicate]在正确位置的javascript文本框中插入文本[重复]
【发布时间】:2012-11-19 14:53:25
【问题描述】:

可能重复:
JavaScript: How can I insert a string at a specific index

假设我的文本框中有这个:

'My name is John'

我想插入这个文本:'Johnson'

到文本框中的 index=11 使其看起来像这样:

'My name is Johnson John'

如何做到这一点?

【问题讨论】:

  • 这是一个简单的任务,到目前为止你尝试过什么?

标签: javascript jquery


【解决方案1】:

您可以使用 jquery 的 .val() 获取该值,然后使用 .slice(11) 在您想要的位置将其分开,与您的新文本连接,然后使用 .val(string) 将其放回文本框。

【讨论】:

    【解决方案2】:

    另一个只是为了好玩解决方案:

    var index = 11,
        word  = "Johnson ";
    
    "My name is John".replace(/./g, function(v, i) {
        return i === index - 1 ? v + word : v;
    });
    

    【讨论】:

      【解决方案3】:

      您还可以创建一个名为 splice 的新原型

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

      Working jsFiddle here

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-01-08
        • 2014-06-03
        • 1970-01-01
        • 1970-01-01
        • 2013-01-24
        • 1970-01-01
        • 2013-10-18
        • 1970-01-01
        相关资源
        最近更新 更多