Tutorials References Menu

JS Tutorial

JS HOME JS Introduction JS Where To JS Output JS Statements JS Syntax JS Comments JS Variables JS Let JS Const JS Operators JS Arithmetic JS Assignment JS Data Types JS Functions JS Objects JS Events JS Strings JS String Methods JS String Search JS Numbers JS Number Methods JS Arrays JS Array Methods JS Array Sort JS Array Iteration JS Array Const JS Dates JS Date Formats JS Date Get Methods JS Date Set Methods JS Math JS Random JS Booleans JS Comparisons JS Conditions JS Switch JS Loop For JS Loop For In JS Loop For Of JS Loop While JS Break JS Typeof JS Type Conversion JS Bitwise JS RegExp JS Errors JS Scope JS Hoisting JS Strict Mode JS this Keyword JS Arrow Function JS Classes JS JSON JS Debugging JS Style Guide JS Best Practices JS Mistakes JS Performance JS Reserved Words

JS Objects

Object Definitions Object Properties Object Methods Object Display Object Accessors Object Constructors Object Prototypes Object Reference Object Map() Object Set()

JS Functions

Function Definitions Function Parameters Function Invocation Function Call Function Apply Function Closures

JS Classes

Class Intro Class Inheritance Class Static

JS Async

JS Callbacks JS Asynchronous JS Promises JS Async/Await

JS Versions

JS Versions JS 2009 (ES5) JS 2015 (ES6) JS 2016 JS 2017 JS 2018 JS IE / Edge JS History

JS HTML DOM

DOM Intro DOM Methods DOM Document DOM Elements DOM HTML DOM Forms DOM CSS DOM Animations DOM Events DOM Event Listener DOM Navigation DOM Nodes DOM Collections DOM Node Lists

JS Browser BOM

JS Window JS Screen JS Location JS History JS Navigator JS Popup Alert JS Timing JS Cookies

JS Web APIs

Web API Intro Web Forms API Web History API Web Storage API Web Worker API Web Fetch API Web Geolocation API

JS AJAX

AJAX Intro AJAX XMLHttp AJAX Request AJAX Response AJAX XML File AJAX PHP AJAX ASP AJAX Database AJAX Applications AJAX Examples

JS JSON

JSON Intro JSON Syntax JSON vs XML JSON Data Types JSON Parse JSON Stringify JSON Objects JSON Arrays JSON Server JSON PHP JSON HTML JSON JSONP

JS vs jQuery

jQuery Selectors jQuery HTML jQuery CSS jQuery DOM

JS Examples

JS Examples JS HTML DOM JS HTML Input JS HTML Objects JS HTML Events JS Browser JS Editor

JS References

JavaScript Objects HTML DOM Objects


JavaScript String Methods


String methods help you to work with strings.


String Methods and Properties

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

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


String Length

The length property returns the length of a string:

Example

let txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
txt.length     // Returns 26
Try it Yourself »

Extracting String Parts

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

  • slice(start, end)
  • substring(start, end)
  • substr(start, length)

The slice() Method

slice() extracts a part of a string and returns the extracted part in a new string.

The method takes 2 parameters: the start position, and the end position (end not included).

This example slices out a portion of a string from position 7 to position 12 (13-1):

Example

let str = "Apple, Banana, Kiwi";
str.slice(7, 13)     // Returns Banana
Try it Yourself »

Remember: JavaScript counts positions from zero. First position is 0.

If a parameter is negative, the position is counted from the end of the string.

This example slices out a portion of a string from position -12 to position -6:

Example

let str = "Apple, Banana, Kiwi";
str.slice(-12, -6)    // Returns Banana
Try it Yourself »

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

Example

str.slice(7);    // Returns Banana,Kiwi
Try it Yourself »

or, counting from the end:

Example

str.slice(-12)    // Returns Banana,Kiwi
Try it Yourself »


The substring() Method

substring() is similar to slice().

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

Example

let str = "Apple, Banana, Kiwi";
substring(7, 13)    // Returns Banana
Try it Yourself »

If you omit the second parameter, substring() will slice out the rest of the string.


The substr() Method

substr() is similar to slice().

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

Example

let str = "Apple, Banana, Kiwi";
str.substr(7, 6)    // Returns Banana

The result of res will be:

Banana
Try it Yourself »

If you omit the second parameter, substr() will slice out the rest of the string.

Example

let str = "Apple, Banana, Kiwi";
str.substr(7)    // Returns Banana,Kiwi
Try it Yourself »

If the first parameter is negative, the position counts from the end of the string.

Example

let str = "Apple, Banana, Kiwi";
str.substr(-4)    // Returns Kiwi
Try it Yourself »

Replacing String Content

The replace() method replaces a specified value with another value in a string:

Example

let text = "Please visit Microsoft!";
let newText = text.replace("Microsoft", "W3Schools");
Try it Yourself »

The replace() method does not change the string it is called on. It returns a new string.

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

Example

let text = "Please visit Microsoft and Microsoft!";
let newText = text.replace("Microsoft", "W3Schools");

Try it Yourself »

By default, the replace() method is case sensitive. Writing MICROSOFT (with upper-case) will not work:

Example

let text = "Please visit Microsoft!";
let newText = text.replace("MICROSOFT", "W3Schools");

Try it Yourself »

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

Example

let text = "Please visit Microsoft!";
let newText = text.replace(/MICROSOFT/i, "W3Schools");

Try it Yourself »

Note that regular expressions are written without quotes.

To replace all matches, use a regular expression with a /g flag (global match):

Example

let text = "Please visit Microsoft and Microsoft!";
let newText = text.replace(/Microsoft/g, "W3Schools");

Try it Yourself »

You will learn a lot more about regular expressions in the chapter JavaScript Regular Expressions.


Converting to Upper and Lower Case

A string is converted to upper case with toUpperCase():

Example

let text1 = "Hello World!";       // String
let text2 = text1.toUpperCase();  // text2 is text1 converted to upper
Try it Yourself »

A string is converted to lower case with toLowerCase():

Example

let text1 = "Hello World!";       // String
let text2 = text1.toLowerCase();  // text2 is text1 converted to lower
Try it Yourself »

The concat() Method

concat() joins two or more strings:

Example

let text1 = "Hello";
let text2 = "World";
let text3 = text1.concat(" ", text2);
Try it Yourself »

The concat() method can be used instead of the plus operator. These two lines do the same:

Example

text = "Hello" + " " + "World!";
text = "Hello".concat(" ", "World!");

All string methods return a new string. They don't modify the original string.
Formally said: Strings are immutable: Strings cannot be changed, only replaced.


String.trim()

The trim() method removes whitespace from both sides of a string:

Example

let text = "       Hello World!        ";
text.trim()    // Returns "Hello World!"
Try it Yourself »

JavaScript String Padding

ECMAScript 2017 added two String methods: padStart and padEnd to support padding at the beginning and at the end of a string.

Example

let text = "5";
text.padStart(4,0)    // Returns 0005
Try it Yourself »

Example

let text = "5";
text.padEnd(4,0)     // Returns 5000
Try it Yourself »

String Padding is not supported in Internet Explorer.

Firefox and Safari were the first browsers with support for JavaScript string padding:

Chrome 57 Edge 15 Firefox 48 Safari 10 Opera 44
Mar 2017 Apr 2017 Aug 2016 Sep 2016 Mar 2017

Extracting String Characters

There are 3 methods for extracting string characters:

  • charAt(position)
  • charCodeAt(position)
  • Property access [ ]

The charAt() Method

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

Example

let text = "HELLO WORLD";
text.charAt(0)           // Returns H
Try it Yourself »

The charCodeAt() Method

The charCodeAt() method returns the unicode of the character at a specified index in a string:

The method returns a UTF-16 code (an integer between 0 and 65535).

Example

let text = "HELLO WORLD";

text.charCodeAt(0)       // Returns 72
Try it Yourself »

Property Access

ECMAScript 5 (2009) allows property access [ ] on strings:

Example

let text = "HELLO WORLD";
text[0]                   // returns H
Try it Yourself »

Property access might be a little unpredictable:

  • It makes strings look like arrays (but they are not)
  • If no character is found, [ ] returns undefined, while charAt() returns an empty string.
  • It is read only. str[0] = "A" gives no error (but does not work!)

Example

let text = "HELLO WORLD";
text[0] = "A"             // Gives no error, but does not work
text[0]                   // returns H
Try it Yourself »

If you want to work with a string as an array, you can convert it to an array.


Converting a String to an Array

A string can be converted to an array with the split() method:

Example

text.split(",")          // Split on commas
text.split(" ")          // Split on spaces
text.split("|")          // Split on pipe
Try it Yourself »

If the separator is omitted, the returned array will contain the whole string in index [0].

If the separator is "", the returned array will be an array of single characters:

Example

text.split("")           // Split in characters
Try it Yourself »

Complete String Reference

For a complete reference, go to our Complete JavaScript String Reference.

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