#javascript #vue.js #vuejs2
Вопрос:
Я использовал фильтр vue, чтобы ограничить текст до 100 символов. Я получаю вывод в виде
Tat is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the indu ...
Если вы видите последнее слово indu ...
,. Я не хочу, чтобы между словами было разбиение на несколько символов слова и точек, вместо этого я хочу, чтобы оно было похоже на полное слово, а затем на точки, как показано ниже :
Tat is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's ...
Слово должно заканчиваться через 100 символов, затем ...
его необходимо добавить.
Ниже приведен фильтр Vue, который я использовал, как я могу закончить полным словом, а затем точками вместо нескольких символов последнего слова?
msg = "lt;pgt; Tat is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishinglt;/pgt;n" lt;h2 v-html="this.$options.filters.limitText(msg)" gt;lt;/h2gt; filters: { limitText: function (val) { if(val amp;amp; (val.length gt; 100) { return (val.substr(0, 100) ' ...') } return val; } }
Ответ №1:
Используя регулярное выражение, я придумал это решение:
const msg = `Tat is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing` console.log(msg.substr(0, 100).replace(/sS*$/, ''))
В принципе, после извлечения 100 первых символов я использую регулярное выражение, чтобы найти последний пробел, за которым следуют символы, не являющиеся пробелами, и удаляю их.
Комментарии:
1. Это полностью удаляет последнее слово, теперь я получаю вывод, это просто фиктивный текст в индустрии печати и верстки. Лорем Ипсум был тем самым …
2. Слово всей отрасли удалено
3. @MadasuK Да, слово «индустрия» удалено, так как вам нужны были целые слова. Поскольку
's
industry's
ввод сокращенsubstr
, я предположил, что все слово должно быть удалено.4. Нет, должно присутствовать все последнее слово
5. @MadasuK, тогда вы можете отредактировать свой вопрос, чтобы включить то, что следует или не следует вырезать ? Если
industry's
должно быть сокращено с помощью апострофа, следуетo'neill
ли также сокращать имена, подобныеo
? Это также сократило бы слова на других языках, напримерaujourd'hui
, на французском.
Ответ №2:
1 — получите первые 100 символов
2 — срезайте до указателя следующего пробела или конца текста.
const msg = `Tat is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing` const LAST_INDEX = 99 let msgShort = msg.substring(0,LAST_INDEX) msg.slice(LAST_INDEX,msg.indexOf(' ',LAST_INDEX)) '...' console.log(msgShort)
substr
не рекомендуется использовать. используйтеsubstring
вместо этого.