在反应中显示一个字符串

display a string in react

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

"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("");
}

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

尝试这样的事情:

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 + ' (...)';
};

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

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

Regex demo

  • ^ 字符串开始
  • (?!\s) 断言开头不是空白字符
  • (.{3,10}\S) 捕获 组 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)}`);
});

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

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

希望这对你有用

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 ...

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

您应该检查第 176 个字符是否为 space (" ")。

希望这对你有用。

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
*/

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

import truncate from 'lodash/truncate'

// ...

truncate('This is a long string', {
  'length': 20,
  'separator': ' ',
  'omission': ' ...',
})

// result: 'This is a long ...'