JavaScript Tutorial
JS - Introduction JS - Basic JS - Placement JS - Output JS - Statements JS - Syntax JS - Variables JS - Comments JS - Data Types JS - Operators JS - Operator Precedence JS - Condition JS - Switch JS - Functions JS - Objects JS - Loops For JS - Loops While JS - Break JS - Strings JS - String Methods JS - Numbers JS - Number Methods JS - Arrays JS - Array Methods JS - Array Iteration JS - Events JS - Event Listener JS - Event Propagation JS - Date JS - Math JS - Random JS - Boolean JS - Type Conversion JS - RegExp JS - Exception JS - Scope JS - Debugging JS - Hoisting JS - Strict Mode JS - this Keyword JS - Mistakes JS - Best Practices JS - Performance JS - Form Validation JS - ES6 Features
JS Objects
Object Definitions Object Properties Object Methods Object Constructors Object Prototypes
JS Functions
Function Definitions Function Parameters Function Call Function Apply Function Closures
JS HTML DOM
DOM Introduction DOM Methods DOM Selectors DOM HTML DOM CSS DOM Attributes DOM Navigation
JS Browser BOM
JS - Window JS - Screen JS - Location JS - History JS - Navigator JS - Popup Alert JS - Timing JS - Cookies
JS AJAX
AJAX - Introduction AJAX - XMLHttp AJAX - Request AJAX - Response AJAX - PHP
JS JSON
JSON - Introduction JSON - Syntax JSON - Data Types JSON - Parse JSON - Stringify JSON - Objects JSON - Arrays JSON - PHP JSON - JSONP
JS References
JavaScript Reference JavaScript Methods HTML DOM Reference

JavaScript String Methods

In previous chapter we've looked at the very basics of strings, let's move up a gear and start thinking about what useful operations we can do on strings with built-in methods and properties.

Primitive values, like "New Delhi", cannot have properties or methods (because they are not objects).

But in JavaScript, methods and properties are also available to primitive values, because JavaScript treats primitive values as objects when executing methods and properties.


Finding the length of a string

The length property returns the length of a string. For an empty string, length is 0.

Run code

Note: A White-space is also counted as character:


The concat() Method

The concat() method is used to concatenate two or more strings.

Run code

Note: All string methods return a new value. They do not change the original variable.


Converting to Upper or Lower Case

The toUpperCase() method returns the calling string value converted to upper case.

Run code

The toLowerCase() method returns the calling string value converted to lower case.

Run code

Finding a substring in a String

The indexOf() method returns the position (index) of the first occurrence of a specified value in a string.

Run code

Note: The index of the first character is 0, the second character is 1, and so on.

The lastIndexOf() method returns the position (index) of the last occurrence of a specified value in a string.

Run code

Both indexOf() and lastIndexOf() return -1 if the value is not found:

Run code

Both indexOf() and lastIndexOf() accept a second parameter as the starting position for the search:

Run code

Searching for a substring in a String

The search() method executes a search for a match between a regular expression and the string.

If the match is found it will return the position of the first match, and if the match is not found it will return -1:

Run code

The following example demonstrates the use of a regular expression with an i flag (ignore case):

Run code

You will learn more about regular expressions later in this tutorial.



Converting a String to an Array

The split() method splits a string into an array of substrings, and returns the new array.

We will use the split() method to separate the array by a whitespace character, represented by " ".

Run code

Now that we have a new array in the arr variable, we can access each element with an index number:

Run code

In the following example we will use "i" as a separator:

Run code

If an empty string ("") is used as the separator, the string is converted to an array of characters:

Run code

By splitting strings you can determine how many words are in a sentence.


Trimming Whitespace

The trim() method removes white space from both ends of a string, but not anywhere in between. Whitespace can be tabs or spaces.

Run code

This method is a simple way to perform the common task of removing excess whitespace.


Replacing String Values

The replace() method returns a new string with some or all matches of a pattern replaced by a replacement.

The first parameter will be the value to be found, and the second parameter will be the value to replace it with.

Run code

By default, the replace() method replaces only the first match.

To replace all occurrences, use a regular expression with a g flag (global search):

Run code

To replace case insensitive, use a regular expression with an i flag (ignore case):

Run code

You will learn more about regular expressions later in this tutorial.


Extracting String Parts

There are 3 methods for extracting a part of a string:


The slice() Method

The slice() method extracts a section of a string and returns it as a new string, without modifying the original string.

This method takes 2 parameters: the start index, and the end index (end not included).

This example extracts a section of a string from index 3 to index 9 (10-1):

Run code

Note: The index of the first character is 0, the second character is 1, and so on.

Use a negative index to select from the end of the string:

Run code

If you omit the second parameter, this method will slice out the rest of the string:

Run code

The following example uses slice() to extract only the last character:

Run code

The substring() Method

The substring() method is similar to slice() method.

The difference is that substring() cannot accept negative indexes.

Run code

If you omit the second parameter, substring() method will extract the rest of the string:

Run code

The substr() Method

The substr() method is similar to slice() method.

The difference is that the second parameter specifies the length of the extracted part.

The following example uses substr() to extract the characters from index 4 and length is 18:

Run code

If you omit the second parameter, substr() method will extract the rest of the string:

Run code

To extract characters from the end of the string, use a negative index number:

Run code

Accessing String Characters

There are 3 methods for accessing string characters:


The charAt() Method

The charAt() method returns the character at a specified index in a string.

Run code

The following example returns the last character of a string:

Run code

The charCodeAt() Method

The charCodeAt() method returns an integer between 0 and 65535 representing the UTF-16 code unit at the given index.

Run code

Square bracket notation [ ]

You can return any character inside a string by using square bracket notation [].

Inside the square brackets you include the index number of the character you want to return.

Run code

Complete String Reference

For a complete properties and methods reference, visit our JavaScript String Reference.

The reference section contains descriptions and examples of all string properties and methods.