I want to shorten text into first 50 without breaking the text some of the text may/may not have html tag in it since I'm using summernote.code
to send the input text. And now I want to retrieve the text but make it short for first 50 words how do I do that ?
I will get the data first and assigned it with new variable cutDesc = e.description;
then I pass the variable into the function shorten. After it have shorten it then I store it in the variable newDescription
and call it back into axios get function. But it's not working.
example e.description
will look like.
<p><strong style="margin: 0px; padding: 0px; font-family: "Open Sans", Arial, sans-serif; text-align: justify;">Lorem Ipsum</strong>
<span style="font-family: "Open Sans", Arial, sans-serif; text-align: justify;">
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>
This is what I have tried and its not working, how do I fix this ?
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 && cutDesc.length > max ? cutDesc.slice(0, max).split(' ').slice(0, -1).join(' ') : cutDesc
}
newDescription= shorten(cutDesc,50);
CodePudding user response:
in your function you can remove the tags first, then take the first 50 words like so
var shorten = (cutDesc, max) => {
const cleanTextArr = cutDesc.replace(/(<([^>] )>)/gi, "").split(' ');
const firstFifty = cleanTextArr.splice(0, max).join(' ');
console.log(firstFifty);
return firstFifty
}
and call this function inside your promise then
after
cutDesc = e.description;
like this
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>`;
}));
}
}