Как сократить текст до первых 50 слов и вернуть его в детализированную функцию Javascript?

#javascript #jquery

Вопрос:

Я хочу сократить текст до первых 50, не разбивая текст, в некоторых текстах может быть/может не быть html-тега, так как я использую summernote.code его для отправки входного текста. И теперь я хочу получить текст, но сделать его коротким для первых 50 слов, как мне это сделать ?

Сначала я получу данные и назначу им новую переменную cutDesc = e.description; , а затем передам переменную в функцию shorten. После того, как он сократит его, я сохраню его в переменной newDescription и вызову его обратно в функцию axios get. Но это не работает.

пример e.description будет выглядеть так.

 <p><strong style="margin: 0px; padding: 0px; font-family: amp;quot;Open Sansamp;quot;, Arial, sans-serif; text-align: justify;">Lorem Ipsum</strong>
<span style="font-family: amp;quot;Open Sansamp;quot;, Arial, sans-serif; text-align: justify;">
amp;nbsp;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 software like Aldus PageMaker including versions of Lorem Ipsum.</span></p>
 

Это то, что я пробовал, и это не работает, как мне это исправить ?

 let description    = '';
    let newDescription = '';
    
    axios.get(`${url}info?id=${id}`)
      .then(function(res) {
          if (res.data.status == 'success') {
            $("#info_list").html(res.data.result.map((e) => {
    
              cutDesc = e.description;
    
              return `<tr class="tb-item">
                                        <td class="">
                                        ${count  }<br>
                                        </td>
                                        
                                        <td class="tb-data">
                                            <span class="tb-data">
                                                <small>${newDescription}</small>
                                            </span>
                                        </td>
                                    </tr>`;
            }));
          }
        }
    
        function shorten(cutDesc, max) {
          return cutDesc amp;amp; cutDesc.length > max ? cutDesc.slice(0, max).split(' ').slice(0, -1).join(' ') : cutDesc

        }
       
        newDescription= shorten(cutDesc,50);
 

Комментарии:

1. Ты это имеешь в виду? w3schools.com/howto/howto_js_read_more.asp

2. @ДханаД. будет ли это возможно при html tag включении в текст описания ?

3. Вы хотите удалить теги или сохранить их? Идея состоит в том, чтобы иметь только слова, или вы пытаетесь сохранить структуру html как wel?

4. @NarekGevorgyan, если возможно, я хочу их удалить. возможно ли это ?

5. Я бы предложил использовать регулярное выражение в этом случае, добавил ответ ниже 🙂

Ответ №1:

в своей функции вы можете сначала удалить теги, а затем взять первые 50 слов, например так

 var shorten = (cutDesc, max) => {
  const cleanTextArr = cutDesc.replace(/(<([^>] )>)/gi, "").split(' ');
  const firstFifty = cleanTextArr.splice(0, max).join(' ');
  console.log(firstFifty);
  return firstFifty
}
 

и вызовите эту функцию внутри вашего обещания then после
cutDesc = e.description; подобный этому

 axios.get(`${url}info?id=${id}`)
      .then(function(res) {
          if (res.data.status == 'success') {
            $("#info_list").html(res.data.result.map((e) => {
    
              cutDesc = e.description;
              newDescription = shorten(cutDesc, 50);
              return `<tr class="tb-item">
                                        <td class="">
                                        ${count  }<br>
                                        </td>
                                        
                                        <td class="tb-data">
                                            <span class="tb-data">
                                                <small>${newDescription}</small>
                                            </span>
                                        </td>
                                    </tr>`;
            }));
          }
        } 

Комментарии:

1. как мне позвонить firstFifty в newDescription «в»?