Benjamin W Benjamin W - 10 days ago 5
Javascript Question

jquery append() in string position

<div contenteditable="true">
abcde<img src="abc.jp" />fg
</div>

$('div').append('<img src="abc.jpg" />'); //this will append img at end of text


I try to add an image into div in position 6

Is any way to append image in position?

Answer

get the text of the div split it at the specified position and concatenate it agian. Then override the html of the div:

var a = $.trim($('div').text());
var b = '<img src="https://jsfiddle.net/img/logo.png" />';
var position = 5;
var output = a.substr(0, position) + b + a.substr(position);
$('div').html(output);

Example


Notes

Using .substr() seems to be faster than .splice

I use $.trim() to avoid a wrong position count due to whitespace or linebreaks

The position is set to 5 because .substr() starts counting at 0