简体   繁体   中英

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

因此,我基本上需要使用split并在每第10个单词之后添加“ ...”,因此我不打算计算单词,而是考虑对空格进行计数,因此,我想在每10个空格字符之后添加“ ...”,那用正则表达式空格字符完成?

You can do something like this.

First split your string on space so you will have an array of strings.

var arr = str.split(' ');

instead of counting spaces you can jump 10 indices in a loop like this.

for(var i = 0; i < arr.length; i = i + 10){
   arr.splice(i, 0, '...');
}

Now to revert the spacing between the words that was before splitting, Here is an additional line of code.

for(var i = 1; i < arr.length; i = i+=2){
   arr.splice(i, 0, ' ');
}

We know after every index there was a space before splitting.

Then you can combine your arr again by looping through it.

var newString = '';

for(var i = 0; i < arr.length; i++){
   newString = newString + arr[i];
}

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

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);
        console.log(i)
    }
    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));
});

Do it with less code:

const text = 'this is some sample text that should be cut after the tenth space character'
let cut_text = text.split(' ').slice(0, 10).join(' ').concat('...')

Will return: this is some sample text that should be cut after...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM