【问题标题】:display a string in react在反应中显示一个字符串
【发布时间】:2021-05-24 01:57:54
【问题描述】:

我有一个如下所示的字符串,我想在特定字符限制后截断它并显示一个省略号。

"This is a long string"

在截断时,我希望字符串显示如下:

This is a long (...)

or

This is a (...)

or

This is (...)

上面的例子没有删减字眼。我不想要的是:

This is a lon (...)

or

This is a long s (...)

上面的例子都不行。

我正在使用以下函数来截断字符串。该功能的问题在于它有时会截断单词。我使用的长度值是 175。 对于 175 个字符的限制,有时会删减单词,有时不会。

export const wordsTruncate = (words, length) => {
    const j = words.split('');
    let result = j.filter((z, a) => a <= (length - 1));

    return result.join("");
}

我想知道我需要在上面的函数中进行哪些更改,以便它不会像上面的示例中所示那样截断单词。

【问题讨论】:

  • 如果有一个像600000个随机字符这样的大词怎么办?除此之外,在这里使用.slice() 似乎更容易——比如说words.slice(0, length).split(/\s+/)?您的 .split("") 只是拆分字母,而不是单词。
  • @ggorlen 感谢您的回答。我想知道你能不能举个例子来解释一下。
  • 我不确定您对此的应用,但如果您在网页上显示文本。 CSS 规则将为您处理此问题。
  • @ggorlen 我试过你的答案,但没有用。

标签: reactjs string substring


【解决方案1】:

试试这个。希望这对你有用。

const wordsTruncate = (words, length) => {
  words = words.trim(); //you need to decied wheather you do this or not
  length -= 6; // because ' (...)'.length === 6
  if (length >= words.length) return words;

  let oldResult = /\s/.test(words.charAt(length));
  for (let i = length - 1; i > -1; i--) {
    const currentRusult = /\s/.test(words.charAt(i))

    //check if oldresult is white space and current is not.
    //which means current character is end of word
    if (oldResult && !currentRusult) {
      return `${words.substr(0, i + 1)} (...)`;
    }
    oldResult = currentRusult;
  }
  // you need to decide whether you will just return truncated or original
  // in case you want original just return word
  return '(...)';
}

console.log(wordsTruncate('This is long text blabla blasdf test.', 32));
console.log(wordsTruncate('This is', 22));
console.log(wordsTruncate('This is', 7));
console.log(wordsTruncate('This is', 13));
console.log(wordsTruncate('This is ', 13));
console.log(wordsTruncate('Thisadsfasdfasdfasdfasdf', 22));

所以长度应该是截断字符串的最终长度。

例如:'This is long text blabla (...)'.length

【讨论】:

    【解决方案2】:

    您可以使用动态模式,在该模式中,您可以在希望省略号起作用的字符串的开头指定最少字符数,以及字符数的长度。

    ^(?!\s)(.{3,10}\S)(?!\S).*
    

    Regex demo

    • ^ 字符串开始
    • (?!\s) 在开头断言不是空白字符
    • (.{3,10}\S) 捕获 group 1(在示例代码中用 m[1] 表示),匹配任意字符的 3 - 10 次,然后匹配末尾的非空白字符
    • (?!\S) 负前瞻,在右侧断言空白边界
    • .* 匹配该行的其余部分

    const wordsTruncate = (s, minNrOfChars, length) => {
      if (minNrOfChars > length || minNrOfChars < 1 || length < 1) return s;
      minNrOfChars--;
      length--;
      const regex = new RegExp(`^(?!\\s)(.{${minNrOfChars},${length}\}\\S)(?!\\S).*`);
      const m = s.match(regex);
      return m ? `${m[1]} (...)` : s;
    }
    
    const strings = [
      "This is a long string",
      "a b c d e f g h",
      "a b c d e       ",
      "a b",
      "this isatest",
      "thisisatesttesttest",
      "A bcdefghifkkle",
      "a",
      "ab",
      "abc",
      "abcd",
      "abcde"
    ];
    
    strings.forEach(s => {
      console.log(`"${s}" --> ${wordsTruncate(s, 3, 10)}`);
    });

    【讨论】:

      【解决方案3】:

      如果你在你的 React 项目中使用 lodash,我们大多数人都会这样做,请像这样使用它的 truncate 方法

      import truncate from 'lodash/truncate'
      
      // ...
      
      truncate('This is a long string', {
        'length': 20,
        'separator': ' ',
        'omission': ' ...',
      })
      
      // result: 'This is a long ...'
      

      【讨论】:

        【解决方案4】:

        试试这样的:

        export const wordsTruncate = (str, length) => {
          const words = str.split(' ');
          const result = words.reduce((acc, it) => {
            const parcial = acc + ' ' + it;
            return parcial.length >= length ? acc : parcial;
          }, '');
        
          return result + ' (...)';
        };
        

        【讨论】:

          【解决方案5】:

          [我使用的长度值是175。对于175个字符的限制,有时会切字有时不会。]

          您应该检查第 176 个字符是否为空格(“”)。

          【讨论】:

            【解决方案6】:

            我希望这对你有用。

            function truncateWords(string, maxLen) {
                if (maxLen >= string.length) return string;
                if (string[maxLen - 6] == ' ') {
                    return string.slice(0, maxLen - 5).split(' ').join(' ') + ' (...)';
                }
                return string.slice(0, maxLen - 5).split(' ').slice(0, -1).join(' ') + ' (...)';
            }
            const strings = [
              "abcdefghijklmno",
              "This is a long string",
              "a b c d e f g h",
              "a b c d e f g h i",
              "a b c d e       ",
              "a b",
              "this isatest",
              "thisisatesttesttest",
              "A bcdefghifkkle",
              "a",
              "ab",
              "abc",
              "abcd",
              "abcde"
            ];
            strings.forEach(function(string) {
              console.log(truncateWords(string, 15));
            });
            
            /* result
            abcdefghijklmno
            This is a  (...)
            a b c d e f g h
            a b c d e  (...)
            a b c d e  (...)
            a b
            this isatest
             (...)
            A bcdefghifkkle
            a
            ab
            abc
            abcd
            abcde
            */

            【讨论】:

              【解决方案7】:

              希望这对你有用

              const truncateWord = (string, length) => {
                if (string.length < length) {
                  return `${string} (...)`;
                }
                return `${string.substring(0, string.substring(0, length).lastIndexOf(" "))} (...)`;
              };
              
              console.log(truncateWord("The quick brown fox jumps over the lazy dog", 10));
              
              
              

              结果

              The quick ...
              

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 2021-07-03
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2023-03-21
                • 1970-01-01
                • 2012-12-01
                相关资源
                最近更新 更多