簡體   English   中英

有沒有辦法將字符串截斷為某些字符而不會在單詞之間結尾

[英]is there way to truncate string upto certain characters without ending in between words

我在java使用一些代碼將某些字符串截斷到某些字符,但不在單詞之間截斷。 這是我在java中使用的代碼

public static String truncateTo(String originalText, int len) {
    if (originalText.length() > len) {
        if (originalText.charAt(len) != ' ') {
            for (int x=len-1;x>=0;x--) {
                if (Character.isWhitespace(originalText.charAt(x))) {
                    return originalText.substring(0, x);
                }
            }
        }
        // default if none of the conditions are met
        return originalText.substring(0, len);
    }
    return originalText;
}

我對javascript有相同要求。 到目前為止嘗試過

if ($('#notificationData').html().length > 60) {
    if ($('#notificationData').html().charAt(60) != ' ') {
        for (var x=60-1;x>=0;x--) {
            if ($('#notificationData').html().charAt(x)) {
                    return $('#notificationData').html().substring(0, x);
            }
        }
    }
      // default if none of the conditions are met
    console.log( $('#notificationData').html().substring(0, len));
}

您有一個錯誤

if ($('#notificationData').html().charAt(x)) {

您不檢查空格

在正確的(和重構的)代碼下面

function truncateTo(originalText, len) {

    if (originalText.length > len) {
        if (originalText[len] != ' ') {
            for (var x = len-1; x >= 0; x--) {
                if (originalText[x] == ' ') {
                    return originalText.substring(0, x);
                }
            }
        }

        return originalText.substring(0, len);
    }

    return originalText;
}

暫無
暫無

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

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