JavaScript & jQuery Tutorials

JS Home Right Arrow JS Reference Right Arrow String Right Arrow substr()

substr()  String  instance method

Description

Returns the characters of a section of an existing string.

Syntax


Signature Description
aString.substr(begin[, numChars])Returns the characters of a section of an existing string.

Parameters


Parameter Description
beginThe starting extraction position of the zero-based character index.
  • Positive values greater than length of string return an empty string.
  • Negative values start extraction from the end of the character index backwards, for the number after negation.
  • Negative values greater than length of string start extraction from 0.
numCharsAn integer specifying the number of characters to extract.
  • Optional and defaults to string length.
  • Negative values or 0 return an empty string.

Examples

The code below returns part of a string.


// Create a string variable.
  var anotherSong = 'I like sunshine, I like moonlight';
// Extract part of the string.
alert(anotherSong.substr(2, 4));
// Extract another part of the string.
alert(anotherSong.substr(6, 9));

Press the button below to action the above code:

Related Tutorials

JavaScript Basic Tutorials - Lesson 8 - Strings



  

go to home page Homepage go to top of page Top