簡體   English   中英

Javascript:在最后一個特定字符后切字符串

[英]Javascript: Cut string after last specific character

我正在使用一些Javascript將字符串切成140個字符,而又不會打斷單詞和東西,但是現在我希望文本具有某種意義。 所以我想如果您找到一個字符(就像。,,,:,;等),並且如果字符串是> 110個字符而<140,則將其切成薄片,這樣文本就更有意義了。 這是我所做的事情:其中texto表示文本,longitud表示長度,而arrayDeTextos表示ArrayText。 謝謝。

//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;
}

將字符串分成句子,然后在附加每個句子之前檢查最終字符串的長度。

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.

我認為Martin Konecny的解決方案效果不佳,因為它排除了定界符,從而使文本失去了很多含義。

這是我的解決方案:

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 += 2部分僅對標點符號的“常用”用法(單個點,冒號等)有意義,而沒有像“ hi !!!?!?1!1!”之類的東西。 。

沒有正則表達式拆分,應該會更有效。

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('')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM