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.
Example:
<script>
var text = 'Extract the substring with first 40 characters from this text. Free JavaScript courses and tutorials - coursesweb.net/';

var txt = text.substr(0, 40);        // gets the first 40 characters

// test
alert(txt);           // Extract the substring with first 40 char
</script>
- The first character has index 0.

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 get 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}/g ), then we apply match() 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:
<script>
var text = 'Extract the substring with first 40 characters from this text. Free JavaScript courses and tutorials - coursesweb.net/';
var nrw = 12;                // the number of words we want to extract

var rgxwords = new RegExp('([^ ]*[ ]{0,1}){1,'+nrw+'}', 'g');      // regexp for specified number of spaces

text = text.replace(/\s\s+/g, ' ');        // replace multiple whitespaces whit single space
var txt = text.match(rgxwords)[0];         // get the substring with "nrw" number of words

// test
alert(txt);           // Extract the substring with first 40 characters from this text. Free JavaScript
</script>

Remove the tags

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, remove the tags and get a specified number of characters:
<script>
var text = 'Text content <i class="cls">with HTML tags</i>. Free courses for <b>web masters</b>: coursesweb.net/';

text = text.replace(/\<[^\>]*\>/gi, '');      // remove HTML tags
text = text.replace(/\s\s+/g, ' ');        // replace multiple whitespaces whit single space
var txt = text.substr(0, 35);        // gets the first 35 characters

// test
alert(txt);           // Text content with HTML tags. Free c
</script>

- Example, strip the tags and get a specified number of words:
<script>
var text = 'Text content <i class="cls">with HTML tags</i>. Free courses for <b>web masters</b>: coursesweb.net/';
var nrw = 8;                // the number of words we want to extract

var rgxwords = new RegExp('([^ ]*[ ]{0,1}){1,'+nrw+'}', 'g');      // regexp for specified number of spaces

text = text.replace(/\<[^\>]*\>/gi, '');      // remove HTML tags
text = text.replace(/\s\s+/g, ' ');           // replace multiple whitespaces whit single space
var txt = text.match(rgxwords)[0];            // get the substring with "nrw" number of words

// test
alert(txt);           // Text content with HTML tags. Free courses for
</script>

Daily Test with Code Example

HTML
CSS
JavaScript
PHP-MySQL
Which tag is used to add definition lists into a <dl> element?
<dt> <dd> <li>
<dl>
 <dt>HTML</dt>
  <dd> - Hyper Text Markup Language</dd>
  <dd> - Language for web pages</dd>
</dl>
Which CSS property can hide an element on page, letting an empty space in its place?
display position visibility
#id {
  visibility: hidden;
}
Click on the event which is triggered when the mouse clicks on an object.
onclick onmouseover onfocus
document.getElementById("id").onclick = function(){
  alert("http://CoursesWeb.net/");
}
Indicate the PHP variable that contains the contents of both $_GET, $_POST, and $_COOKIE arrays.
$_SESSION $_GET $_REQUEST
if(isset($_REQUEST["id"])) {
  echo $_REQUEST["id"];
}
Extract a number of characters and words from string

Last accessed pages

  1. HTTP Errors and Logging (39)
  2. Add, Change, and Remove Attributes with jQuery (35999)
  3. Select in MySQL, Output results in HTML Table (3789)
  4. jQuery Drag and Drop Rows between two similar Tables (6875)
  5. PhpSpreadsheet - Read, Write Excel and LibreOffice Calc files (8371)

Popular pages this month

  1. Read Excel file data in PHP - PhpExcelReader (443)
  2. PhpSpreadsheet - Read, Write Excel and LibreOffice Calc files (351)
  3. Register and show online users and visitors (319)
  4. Courses Web: PHP-MySQL JavaScript Ajax HTML CSS Flash-AS3 (300)
  5. Insert, Select and Update NULL value in MySQL (214)