0

Possible Duplicate:
JavaScript: How can I insert a string at a specific index

Let's say I have this in my textbox:

'My name is John'

I want to insert this text: 'Johnson '

to index=11 in the textbox so that it looks like this:

'My name is Johnson John'

How to do this?

4

3 に答える 3

2

You could get the value with jquery's .val(), then break that apart at your desired position with .slice(11), concatenate with your new text, and put it back into the textbox with .val(string).

于 2012-11-19T15:00:40.377 に答える
1

Yet another just-for-fun solution:

var index = 11,
    word  = "Johnson ";

"My name is John".replace(/./g, function(v, i) {
    return i === index - 1 ? v + word : v;
});
于 2012-11-19T15:07:46.367 に答える
0

You can also create a new prototype called splice

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

Working jsFiddle here

于 2012-11-19T15:05:06.137 に答える