clusterBuddy clusterBuddy - 1 year ago 90
HTML Question

JQuery - how to add characters to a string of words after counting X amount of spaces

So I basically need to use split and add "..." after every 10th word, so instead of counting words I thought of counting spaces, so after every 10th space character I would like to add "...", How could that be done with the regex space character?

Answer Source

Actually you don't need RegEx for such a mission... Extending @Umair answer for further functionality you can make a function that you can call on every string you need to this thing with, And to specify the number of words and the divider separately


function insertStrEvery(target, string, count) {

    wordsArr = target.split(' ');

    wordsCount = wordsArr.length;

    for (var i = count; i < wordsCount; i = i+count) {
        wordsArr.splice(i, 0, string);
    newString = wordsArr.join(' ');
    return newString;


Then You can call it on any DOM element that have text

$(document).ready(function() {
    target = $('p').text();
    insertStrEvery(target, '...', 10)
    console.log(insertStrEvery(target, '...', 3));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download