In this tutorial you can learn how to extract in JavaScript a specified number of characters or words from a string / text.
- To get the first "n" characters from a string it's easy, you use the substr() function (the first character has index 0).
Example:
<h4>Example substr()</h4>
<p>Click on the button to display the first 40 characters from the string in the JavaScript text variable.</p>
<button id='btn1'>Click</button>
<blockquote id='resp'>#resp</blockquote>

<script>
var text ='Extract the first 40 characters from this text - coursesweb.net/';

var resp = document.getElementById('resp');
document.getElementById('btn1').addEventListener('click', (ev)=>{
 var str = text.substr(0, 40); // gets the first 40 characters
 resp.innerHTML = str;
});
</script>

Extract a number of specified words

As you can notice in the example above, when we extract a specified number of characters, the last word can be chopped.
If you have a text from which you want to get a substring, and to add a button with "Read more ...", it's better to get the last word complete, as it is. In this case, instead of getting a number of characters, we'll extract a specified number of words.
The words are separated by space, so, we can use a RegExp (Regular expression) pattern to represent a string with a number of spaces according to the number of words we want to extract ( /([^ ]*[ ]{0,1}){1, nr}/ig ), then we apply t7he match() method with that RegExp to get the substring.


- To make sure we have only one space between words, we apply this code:
  text.replace('/\s\s+/g', ' ')   - replaces multiple whitespaces with a single space character, from "text".
Here's an example with the same text:
<h4>Example extract a number of words</h4>
<p>Click on the button to display the first 6 words from the string in the JavaScript text variable.</p>
<button id='btn1'>Click</button>
<blockquote id='resp'>#resp</blockquote>

<script>
var text ='Extract the first 40 characters from this text - coursesweb.net/';
var nrw =6; // the number of words we want to extract
var rgxwords = new RegExp('([^ ]*[ ]{0,1}){1,'+nrw+'}', 'ig'); // regexp for specified number of spaces

var resp = document.getElementById('resp');
document.getElementById('btn1').addEventListener('click', (ev)=>{
 var str = text.replace(/\s\s+/g, ' '); // replace multiple whitespaces whit single space
 str = str.match(rgxwords)[0]; // get the substring with 'nrw' number of words
 resp.innerHTML = str;
});
</script>

Removing the tags from strings in JavaScript

If the text-content contains HTML tags, when you extract a substring from that content, it is very posible to get opened tags, which will affect the content format when you add that substring in the page. In this case, it's better to remove the tags before extracting the number of characters, or words.
To remove HTML tags in JavaScript, you can use:   text.replace(/\<[^\>]*\>/gi, '').


- Example, removing the tags from a string and get a specified number of characters:
<h4>Example reemoving the tags from string</h4>
<p>Click on the button to display the first 35 characters from the HTML string in the JavaScript text variable.</p>
<button id='btn1'>Click</button>
<blockquote id='resp'>#resp</blockquote>

<script>
var text = 'Text content <em class="cls">with HTML tags</em>. Free courses for <b>web masters</b>: coursesweb.net/';
var nrw =6; // the number of words we want to extract
var rgxwords = new RegExp('([^ ]*[ ]{0,1}){1,'+nrw+'}', 'ig'); // regexp for specified number of spaces

var resp = document.getElementById('resp');
document.getElementById('btn1').addEventListener('click', (ev)=>{
 var str = text.replace(/\<[^\>]*\>/gi, ''); // removes HTML tags
 str = str.replace(/\s\s+/g, ' '); // replace multiple whitespaces whit single space
 str = str.substr(0, 35); // gets the first 35 characters
 resp.innerHTML = str;
});
</script>

Daily Test with Code Example

HTML
CSS
JavaScript
PHP-MySQL
Which tag is used to add lists into <ul> and <ol> elements?
<dt> <dd> <li>
<ul>
 <li>http://coursesweb.net/html/</li>
 <li>http://coursesweb.net/css/</li>
</ul>
Which value of the "display" property creates a block box for the content and ads a bullet marker?
block list-item inline-block
.some_class {
  display: list-item;
}
Which instruction converts a JavaScript object into a JSON string.
JSON.parse() JSON.stringify eval()
var obj = {
 "courses": ["php", "javascript", "ajax"]
};
var jsonstr = JSON.stringify(obj);
alert(jsonstr);    // {"courses":["php","javascript","ajax"]}
Indicate the PHP class used to work with HTML and XML content in PHP.
stdClass PDO DOMDocument
$strhtml = '<body><div id="dv1">CoursesWeb.net</div></body>';
$dochtml = new DOMDocument();
$dochtml->loadHTML($strhtml);
$elm = $dochtml->getElementById("dv1");
echo $elm->nodeValue;    // CoursesWeb.net
Extract a number of characters and words from string

Last accessed pages

  1. Contact page - CoursesWeb (10968)
  2. Tabs effect with CSS (11675)
  3. Making DIV Contents Scroll Horizontally, with multiple Div`s inside (17574)
  4. PhpSpreadsheet - Read, Write Excel and LibreOffice Calc files (15674)
  5. SHA512 Encrypt hash in JavaScript (12625)

Popular pages this month

  1. Making DIV Contents Scroll Horizontally, with multiple Div`s inside (1975)
  2. Contact page - CoursesWeb (1923)
  3. Tabs effect with CSS (1923)
  4. Insert, Select and Update NULL value in MySQL (1228)
  5. PHP getElementById and getElementsByTagName (722)