【问题标题】:Truncated a string with a number of characters without truncating words截断包含多个字符的字符串而不截断单词
【发布时间】:2019-01-03 15:59:33
【问题描述】:

我想截断一个有字符限制的字符串,最后一个字符的条件应该是空格(这样我就没有截断的单词)

例子:

var sentence = "The string that I want to truncate!";
sentence.methodToTruncate(14); // 14 is the limit of max characters 
console.log("Truncated result : " + sentence); // Truncated result : The string 

【问题讨论】:

  • 好的,那么到目前为止你尝试了什么?
  • 是的,我们需要努力,我们不能只为您编写代码
  • 为什么不在javascript中使用substring()方法?
  • @Nerdvoso:我不认为这符合我们的建议。 sentence.substring(0, 14) 更接近,但忽略了避免部分单词的问题。解决方案并不难,但我希望看到 OP 在发布之前付出一些努力。

标签: javascript truncate


【解决方案1】:

您可以在下面使用truncate 单行:

const sentence = "The string that I want to truncate!";

const truncate = (str, len) => str.substring(0, (str + ' ').lastIndexOf(' ', len));

console.log(truncate(sentence, 14));

【讨论】:

    【解决方案2】:

    以下是如何按单词和给定限制截断 -

    String.prototype.methodToTruncate = function(n) {
        var parts = this.split(" ");
        var result = "";
        var i = 0;
        while(result.length >= n || i < parts.length) {
           if (result.length + parts[i].length > n) {
               break;
           }
           
           result += " " + parts[i];
           i++;
        }
        
        return result;
    }
    
    var sentence = "The string that I want to truncate!";
    console.log("Truncated result : " + sentence.methodToTruncate(14)); // Truncated result : The string

    【讨论】:

    • 感谢您的回答:)
    【解决方案3】:

    首先,您可以拥有字符串的最大子字符串,然后递归删除字母,直到找到空格。 请注意,此响应是在没有进行猴子修补的情况下做出的,因此不会扩展 String.prototype :

    var sentence = "Hello a";
    var a = methodToTruncate(sentence, 5); // 14 is the limit of max characters 
    console.log("Truncated result : " + a); // Truncated result : The string 
    
    function methodToTruncate(str, num) {
    
    	if(num>= str.length){ return str;}
      var res = str.substring(0, num);
      
      while (str[res.length] != " " && res.length != 0) {
        console.log(res.length)
        res = res.substring(0, res.length-1);
      }
      return res;
    }

    【讨论】:

    • 感谢您的回答:)
    猜你喜欢
    • 2021-10-28
    • 1970-01-01
    • 2011-10-02
    • 1970-01-01
    • 2022-07-05
    • 2018-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多