简体   繁体   中英

Javascript: Cut string after last specific character

I'm doing some Javascript to cut strings into 140 characters, without breaking words and stuff, but now i want the text so have some sense. so i would like if you find a character (just like ., , :, ;, etc) and if the string is>110 characters and <140 then slice it, so the text has more sense. Here is what i have done: where texto means text, longitud means length, and arrayDeTextos means ArrayText. Thank you.

//function to cut strings
function textToCut(texto, longitud){
    if(texto.length<longitud) return texto;
    else {
        var cortado=texto.substring(0,longitud).split(' ');
        texto='';
        for(key in cortado){
            if(key<(cortado.length-1)){
                texto+=cortado[key]+' ';
                if(texto.length>110 && texto.length<140) {
                    alert(texto);
                }
        }
      }
    }
    return texto;
}

function textToCutArray(texto, longitud){
    var arrayDeTextos=[];
    var i=-1;
    do{
        i++;
        arrayDeTextos.push(textToCut(texto, longitud));
        texto=texto.replace(arrayDeTextos[i],'');
    }while(arrayDeTextos[i].length!=0)
        arrayDeTextos.push(texto);
    for(key in arrayDeTextos){
        if(arrayDeTextos[key].length==0){
          delete arrayDeTextos[key];
        }
  }
    return arrayDeTextos;
}

Break the string into sentences, then check the length of the final string before appending each sentence.

var str = "Test Sentence. Test Sentence";
var arr = str.split(/[.,;:]/) //create an array of sentences delimited by .,;:

var final_str = ''
for (var s in arr) {
    if (final_str.length == 0) {
        final_str += arr[s];
    } else if (final_str.length + s.length < 140) {
        final_str += arr[s];
    }
}

alert(final_str); // should have as many full sentences as possible less than 140 characters.

I think Martin Konecny's solution doesn't work well because it excludes the delimiter and so removes lots of sense from the text.

This is my solution:

var arrTextChunks = text.split(/([,:\?!.;])/g),
    finalText = "",
    finalTextLength = 0;

for(var i = 0; i < arrTextChunks.length; i += 2) {
    if(finalTextLength + arrTextChunks[i].length + 1 < 140) {
        finalText += arrTextChunks[i] + arrTextChunks[i + 1];
        finalTextLength += arrTextChunks[i].length;
    } else if(finalTextLength > 110) { 
        break; 
    }       
}

http://jsfiddle.net/Whre/3or7j50q/3/

I'm aware of the fact that the i += 2 part does only make sense for "common" usages of punctuation (a single dot, colon etc.) and nothing like "hi!!!?!?1!1!".

Should be a bit more effective without regex splits.

var truncate = function (str, maxLen, delims) {
    str = str.substring(0, maxLen);

    return str.substring(0, Math.max.apply(null, delims.map(function (s) {
        return str.lastIndexOf(s);
    })));
};

试试这个正则表达式,您可以在这里看到它的工作原理: http ://regexper.com/#%5E(%5Cr%5Cn%7C.)%7B1%2C140%7D%5Cb

str.match(/^(\r\n|.){1,140}\b/g).join('')

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