缩短50个字符后的文字,但仅在当前单词之后

发布于 2025-02-10 18:30:06 字数 240 浏览 3 评论 0原文

我需要在50个字符后缩短文字,但是如果第50个字符在一个单词的中间 - 仅在单词之后切下,而不是以前。

示例文本: 与普遍的看法相反,Lorem Ipsum不仅是文本(59个字符)

预期输出:与普遍的看法相反,Lorem Ipsum不仅是(54个字符),

而且我正在尝试: text.substr(0,50).lastIndexof('')); - 对我不利,因为它剪切了“简单的”,我想简单地属于缩短文本。 感谢您的帮助!

I need to shorten text after 50 characters but if the 50th char is at the middle of a word - cut only after the word and not before.

example text:
Contrary to popular belief, Lorem Ipsum is not simply text (59 chars)

expected output: Contrary to popular belief, Lorem Ipsum is not simply (54 chars)

I was trying this:
text.substr(0,50).lastIndexOf(' ')); - not good for me cause it cuts of the "simply" and I want the simply to be at the shorten text.
Thanks for the help!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

扛起拖把扫天下 2025-02-17 18:30:06

如果短语长度小于极限,请返回短语;否则,将切片索引设置为极限并扫描,直到找到一个单词边界并切成短语。

const clip = (phrase, limit) => {
  if (phrase.length <= limit) return phrase;
  let sliceIndex = limit;
  while (sliceIndex < phrase.length && /\b/.test(phrase[sliceIndex])) sliceIndex++;
  return phrase.slice(0, sliceIndex);
};

const input = "Contrary to popular belief, Lorem Ipsum is not simply text";

const expected = "Contrary to popular belief, Lorem Ipsum is not simply";

const actual = clip(input, 50);

console.log(actual === expected); // true

If the phrase length is less than the limit, return the phrase; else, set the slice index to the limit and scan until you find a word boundary and slice the phrase.

const clip = (phrase, limit) => {
  if (phrase.length <= limit) return phrase;
  let sliceIndex = limit;
  while (sliceIndex < phrase.length && /\b/.test(phrase[sliceIndex])) sliceIndex++;
  return phrase.slice(0, sliceIndex);
};

const input = "Contrary to popular belief, Lorem Ipsum is not simply text";

const expected = "Contrary to popular belief, Lorem Ipsum is not simply";

const actual = clip(input, 50);

console.log(actual === expected); // true

美羊羊 2025-02-17 18:30:06

正则表达可以帮助您。
这个想法是找到至少50个以Word Boundare \ B结束的符号

let text = 'Contrary to popular belief, Lorem Ipsum is not simply text';
let shortetedText = text.match(/.{50,}?(?=\b)/)[0];
console.log(shortetedText);

upd:
如果要创建一个函数,该函数如果文本超过50个符号,则可以创建一个可以执行此功能而不是您的函数。

let short = text => text.length > 50 ? text.match(/.{50,}?(?=\b)/)[0]: text;  

然后只是这样使用:

let longText = 'Contrary to popular belief, Lorem Ipsum is not simply text';
let shortText = 'Lorem ipsum';
console.log(short(longText)); //will shorten text
console.log(short(shortText)); //will leave text as it is bcoz it's shorter than 50 symbols

Regular expression can help you with it.
The idea is to find at least 50 symbols that finishes with word boundary \b

let text = 'Contrary to popular belief, Lorem Ipsum is not simply text';
let shortetedText = text.match(/.{50,}?(?=\b)/)[0];
console.log(shortetedText);

UPD:
If you want to create a function that shorten your text if it's longer than 50 symbols we can create a function that do it instead of you.

let short = text => text.length > 50 ? text.match(/.{50,}?(?=\b)/)[0]: text;  

Then just use it like that:

let longText = 'Contrary to popular belief, Lorem Ipsum is not simply text';
let shortText = 'Lorem ipsum';
console.log(short(longText)); //will shorten text
console.log(short(shortText)); //will leave text as it is bcoz it's shorter than 50 symbols
紧拥背影 2025-02-17 18:30:06

您与sudstring&amp;索引。如果您在前50个字符之后寻找空间,则可以使用。然后是一个边缘情况,字符串长于50个字符而没有空间。

const shortener = (str) => {
  const offset = str.substring(50).indexOf(' '); 
  return offset !== -1   ? str.substring(0,50 + offset) + '...' : 
         str.length > 50 ? str + '...' : str;
}

You were close with the substring & indexOf. If you look for a space after the first 50 characters it will work. Then there is an edge case where the string is longer then 50 characters and no space.

const shortener = (str) => {
  const offset = str.substring(50).indexOf(' '); 
  return offset !== -1   ? str.substring(0,50 + offset) + '...' : 
         str.length > 50 ? str + '...' : str;
}
人事已非 2025-02-17 18:30:06
const text ="Contrary to popular belief, Lorem Ipsum is not simply text"


// start of the last word 
const start =  text.substr(0,50).lastIndexOf(' ')
// start from where you left + 1 to remove space
const end = text.substr(start+1,text.length).indexOf(' ')

console.log(text.substr(0,start + end + 1));
const text ="Contrary to popular belief, Lorem Ipsum is not simply text"


// start of the last word 
const start =  text.substr(0,50).lastIndexOf(' ')
// start from where you left + 1 to remove space
const end = text.substr(start+1,text.length).indexOf(' ')

console.log(text.substr(0,start + end + 1));
雨轻弹 2025-02-17 18:30:06

下一条言论的一线式

一线似乎似乎是多余的,但实际上它们在那里覆盖边缘案例。

// Length fixed at "50"
const trim50 = str => str?.match(/^.{0,50}.*?(?=\b| |$)/)[0];

// Dynamic length
const trim = (str, n) => new RegExp(`^.{0,${n}}.*?(?=\b| |$)`).exec(str)[0];

// Demo
console.log(trim('Contrary to popular belief, Lorem Ipsum is not simply text', 50))

无正

const trim = (str, n) => {
  const start = str.substring(0, n);
  const index = str.indexOf(' ', n - 1);
  const end   = str.slice(n, index < 0 ? str.length : index);
  return start + end;
}

console.log(trim('Contrary to popular belief, Lorem Ipsum is not simply text', 50));

测试案例

由于SO内置控制台的局限性, ,请使用F12提升DevTools的控制台,然后然后 运行以下代码以进行一些演示。

const testCases = [
  { input:    'Contrary to popular belief, Lorem Ipsum is not simply text',
    expected: 'Contrary to popular belief, Lorem Ipsum is not simply' },
  { input:    '1234 6789 1234 6789 1234 6789 1234 6789 1234 678901234 6789',
    expected: '1234 6789 1234 6789 1234 6789 1234 6789 1234 678901234' },
  { input:    '1234 6789 1234 6789 1234 6789 1234 6789 1234 6789 1234 6789',
    expected: '1234 6789 1234 6789 1234 6789 1234 6789 1234 6789 ' },
  { input:    '1234 6789 1234 6789 1234 6789 1234 6789 1234 67890123456789',
    expected: '1234 6789 1234 6789 1234 6789 1234 6789 1234 67890123456789' },
  { input:    '                                                            ',
    expected: '                                                  ' },
  { input:    '1234 5678',
    expected: '1234 5678' },
  { input:    '1234',
    expected: '1234' },
  { input:    '',
    expected: '' }
];

const test = trim => {
  console.table(
    testCases.map(
      testCase => Object.assign(
        Object.assign(testCase, { output: trim(testCase.input) }),
        { pass: testCase.output === testCase.expected }
      )
    )
  );
};

test(str => str?.match(/^.{0,50}.*?(?=\b| |$)/)[0]);

Regex one-liners

Parts of the below regexes may seem redundant, but they are actually there to cover the edge cases.

// Length fixed at "50"
const trim50 = str => str?.match(/^.{0,50}.*?(?=\b| |$)/)[0];

// Dynamic length
const trim = (str, n) => new RegExp(`^.{0,${n}}.*?(?=\b| |$)`).exec(str)[0];

// Demo
console.log(trim('Contrary to popular belief, Lorem Ipsum is not simply text', 50))

Regex-free

const trim = (str, n) => {
  const start = str.substring(0, n);
  const index = str.indexOf(' ', n - 1);
  const end   = str.slice(n, index < 0 ? str.length : index);
  return start + end;
}

console.log(trim('Contrary to popular belief, Lorem Ipsum is not simply text', 50));

Test cases

Due to the limitations of the SO's built-in console, please first bring up the DevTools's console with F12, and then run the below code for a little demo.

const testCases = [
  { input:    'Contrary to popular belief, Lorem Ipsum is not simply text',
    expected: 'Contrary to popular belief, Lorem Ipsum is not simply' },
  { input:    '1234 6789 1234 6789 1234 6789 1234 6789 1234 678901234 6789',
    expected: '1234 6789 1234 6789 1234 6789 1234 6789 1234 678901234' },
  { input:    '1234 6789 1234 6789 1234 6789 1234 6789 1234 6789 1234 6789',
    expected: '1234 6789 1234 6789 1234 6789 1234 6789 1234 6789 ' },
  { input:    '1234 6789 1234 6789 1234 6789 1234 6789 1234 67890123456789',
    expected: '1234 6789 1234 6789 1234 6789 1234 6789 1234 67890123456789' },
  { input:    '                                                            ',
    expected: '                                                  ' },
  { input:    '1234 5678',
    expected: '1234 5678' },
  { input:    '1234',
    expected: '1234' },
  { input:    '',
    expected: '' }
];

const test = trim => {
  console.table(
    testCases.map(
      testCase => Object.assign(
        Object.assign(testCase, { output: trim(testCase.input) }),
        { pass: testCase.output === testCase.expected }
      )
    )
  );
};

test(str => str?.match(/^.{0,50}.*?(?=\b| |$)/)[0]);

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文