Get the first N words with Javascript
236
post-template-default,single,single-post,postid-236,single-format-standard,bridge-core-3.0.1,qodef-qi--no-touch,qi-addons-for-elementor-1.5.3,qode-page-transition-enabled,ajax_updown,page_not_loaded,,vertical_menu_enabled,side_area_uncovered_from_content,qode-theme-ver-28.7,qode-theme-bridge,disabled_footer_top,qode_header_in_grid,wpb-js-composer js-comp-ver-6.8.0,vc_responsive,elementor-default,elementor-kit-6

Get the first N words with Javascript

Get the first N words with Javascript

Here’s how I get the first 20 words using a regular expression and the Javascript replace function. I place an ellipsis at the end to indicate that the sentence was shortened:


var str1 = "Here is a sentence that just seems to go on and on. Here is a sentence that just seems to go on and on. Here is a sentence that just seems to go on and on.";
var str2 = str1.replace(/(([^\s]+\s\s*){20})(.*)/,"$1…");
document.write(str2);
// result:
// Here is a sentence that just seems to go on and on. Here is a sentence that just seems to …



Mastodon