How to use String slice() to get substring in Javascript

Slice a string

slice(startingPosition [, whereToStop(exclusive)]) returns a substring and accepts either one or two arguments.

If the second argument is omitted, it is default to the ending position. slice() does not alter the value of the string itself.

Example


var stringValue = "hello world"; 
console.log(stringValue.slice(3)); //"lo world" 

The code above generates the following result.

Example 2

A negative argument tells to do the sub string from the end.


var stringValue = "hello world"; 
        //www  .j  a v a  2 s . c  o m
console.log(stringValue.slice(-3)); //"rld" 
console.log(stringValue.slice(3, -4)); //"lo w" 

The code above generates the following result.





















Home »
  Javascript »
    Javascript Reference »




Array
Canvas Context
CSSStyleDeclaration
CSSStyleSheet
Date
Document
Event
Global
History
HTMLElement
Input Element
Location
Math
Number
String
Window