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 in <table> to create table header cell?
<thead> <th> <td>
<table><tr>
  <th>Title 1</th>
  <th>Title 2</th>
</tr></table>
Which CSS property sets the distance between lines?
line-height word-spacing margin
.some_class {
  line-height: 150%;
}
Which function opens a new browser window.
alert() confirm() open()
document.getElementById("id_button").onclick = function(){
  window.open("http://coursesweb.net/");
}
Indicate the PHP function that returns an array with names of the files and folders inside a directory.
mkdir() scandir() readdir()
$ar_dir = scandir("dir_name");
var_export($ar_dir);
Extract a number of characters and words from string

Last accessed pages

  1. PHP Simple HTML DOM Parser (6968)
  2. Follow the mouse cursor with a DIV inside a Parent (1938)
  3. Add Pause in JavaScript script (7964)
  4. Read Excel file data in PHP - PhpExcelReader (50840)
  5. PhpSpreadsheet - Read, Write Excel and LibreOffice Calc files (3083)

Popular pages this month

  1. Qwop (2996)
  2. Get Attribute (ID, Class, Name, Title, Src) with jQuery (2371)
  3. Get the value of the selected /checked checkboxes in a form (1497)
  4. Insert, Select and Update NULL value in MySQL (1339)
  5. Add, Change, and Remove Attributes with jQuery (1225)