• Home
  • Jobs
  • Courses
  • Certifications
  • Companies
  • Online IDE
  • Login
  • Signup
MYTAT
  • Home
  • Jobs
  • Courses
  • Certifications
  • Companies
  • Online IDE
  • Login
  • Signup
JavaScript
  • JavaScript Introduction
  • JavaScript Where To
  • JavaScript Output
  • JavaScript Statements
  • JavaScript Syntax
  • JavaScript Comments
  • JavaScript Variables
  • JavaScript Let
  • JavaScript Const
  • JavaScript Operators
  • JavaScript Assignment
  • JavaScript Data Types
  • JavaScript Functions
  • JavaScript Objects
  • JavaScript Events
  • JavaScript Strings
  • JavaScript String Methods
  • JavaScript Numbers
  • JavaScript Number Methods
  • JavaScript Arrays
  • JavaScript Array Const
  • JavaScript Array Methods
  • JavaScript Sorting Arrays
  • JavaScript Array Iteration
  • JavaScript Date Objects
  • JavaScript Date Formats
  • JavaScript Get Date Methods
  • JavaScript Set Date Methods
  • JavaScript Math Object
  • JavaScript Random
  • JavaScript Booleans
  • JavaScript Comparison And Logical Operators
  • JavaScript If Else And Else If
  • JavaScript Switch Statement
  • JavaScript For Loop
  • JavaScript Break And Continue
  • JavaScript Type Conversion
  • JavaScript Bitwise Operations
  • JavaScript Regular Expressions
  • JavaScript Errors
  • JavaScript Scope
  • JavaScript Hoisting
  • JavaScript Use Strict
  • The JavaScript This Keyword
  • JavaScript Arrow Function
  • JavaScript Classes
  • JavaScript JSON
  • JavaScript Debugging
  • JavaScript Style Guide
  • JavaScript Common Mistakes
  • JavaScript Performance
  • JavaScript Reserved Words
  • JavaScript Versions
  • JavaScript History
  • JavaScript Forms
  • JavaScript Validation API
  • JavaScript Objects
  • JavaScript Object Properties
  • JavaScript Function Definitions
  • JavaScript Function Parameters
  • JavaScript Function Invocation
  • JavaScript Closures
  • JavaScript Classes
  • Java Script Async
  • JavaScript HTML DOM
  • The Browser Object Model
  • JS Ajax
  • JavaScript JSON
  • JavaScript Web APIs
  • JS Vs JQuery
  • Home
  • Courses
  • JavaScript
  • JavaScript String Methods

JavaScript String Methods

Previous Next

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

var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var sln = txt.length;
Try it now

Finding a String in a String

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

Example

var str = "Please locate where 'locate' occurs!";
var pos = str.indexOf("locate");
 

JavaScript counts positions from zero.
0 is the first position in a string, 1 is the second, 2 is the third ...

The lastIndexOf() method returns the index of the last occurrence of a specified text in a string:

Example

var str = "Please locate where 'locate' occurs!";
var pos = str.lastIndexOf("locate");
 

Both indexOf(), and lastIndexOf() return -1 if the text is not found.

Example

var str = "Please locate where 'locate' occurs!";
var pos = str.lastIndexOf("John");
 

Both methods accept a second parameter as the starting position for the search:

Example

var str = "Please locate where 'locate' occurs!";
var pos = str.indexOf("locate", 15);
 

The lastIndexOf() methods searches backwards (from the end to the beginning), meaning: if the second parameter is 15, the search starts at position 15, and searches to the beginning of the string.

Example

var str = "Please locate where 'locate' occurs!";
var pos = str.lastIndexOf("locate", 15);



Practice Excercise Practice now

Searching For A String In A String

The search() method searches a string for a specified value and returns the position of the match:

Example

var str = "Please locate where 'locate' occurs!";
var pos = str.search("locate");
 

Did You Notice?

The two methods, indexOf() and search(), are equal?

They accept the same arguments (parameters), and return the same value?

The two methods are NOT equal. These are the differences:

  • The search() method cannot take a second start position argument.
  • The indexOf() method cannot take powerful search values (regular expressions).



Practice Excercise Practice now

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

var str = "Apple, Banana, Kiwi";
var res = str.slice(7, 13);
Try it now

The result of res will be:

Banana
 

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

var str = "Apple, Banana, Kiwi";
var res = str.slice(-12, -6);
Try it now

The result of res will be:

Banana

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

Example

var res = str.slice(7);
Try it now

or, counting from the end:

Example

var res = str.slice(-12);
Try it now
Negative positions do not work in Internet Explorer 8 and earlier.
 

The substring() Method

substring() is similar to slice().

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

Example

var str = "Apple, Banana, Kiwi";
var res = str.substring(7, 13);
Try it now

The result of res will be:

Banana

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

var str = "Apple, Banana, Kiwi";
var res = str.substr(7, 6);
Try it now

The result of res will be:

Banana

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

Example

var str = "Apple, Banana, Kiwi";
var res = str.substr(7);
Try it now

The result of res will be:

Banana, Kiwi
 

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

Example

var str = "Apple, Banana, Kiwi";
var res = str.substr(-4);
Try it now

The result of res will be:

Kiwi



Practice Excercise Practice now

Replacing String Content

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

Example

str = "Please visit Microsoft!";
var n = str.replace("Microsoft", "Mytat");
Try it now

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

str = "Please visit Microsoft and Microsoft!";
var n = str.replace("Microsoft", "Mytat");
Try it now
 

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

Example

str = "Please visit Microsoft!";
var n = str.replace("MICROSOFT", "Mytat");
 
Try it now

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

Example

str = "Please visit Microsoft!";
var n = str.replace(/MICROSOFT/i, "Mytat");
 
Try it now

Note that regular expressions are written without quotes.

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

Example

str = "Please visit Microsoft and Microsoft!";
var n = str.replace(/Microsoft/g, "Mytat");
Try it now



Practice Excercise Practice now

Converting To Upper And Lower Case

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

Example

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

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

Example

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



Practice Excercise Practice now

The Concat() Method

concat() joins two or more strings:

Example

var text1 = "Hello";
var text2 = "World";
var text3 = text1.concat(" ", text2);
Try it now

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

Example

var text = "Hello" + " " + "World!";
var 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.



Practice Excercise Practice now

String.trim()

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

Example

var str = "       Hello World!        ";
alert(str.trim());
Try it now

The trim() method is not supported in Internet Explorer 8 or lower.

If you need to support IE 8, you can use replace() with a regular expression instead:

Example

var str = "       Hello World!        ";
alert(str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ''));
 

You can also use the replace solution above to add a trim function to the JavaScript String.prototype:

Example

if (!String.prototype.trim) {
  String.prototype.trim = function () {
    return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
  };
}
var str = "       Hello World!        ";
alert(str.trim());



Practice Excercise Practice now

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 str = "5";
str = str.padStart(4,0);
// result is 0005
Try it now

Example

let str = "5";
str = str.padEnd(4,0);
// result is 5000
 
Try it now

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



Practice Excercise Practice now

Converting A String To An Array

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

Example

var txt = "a,b,c,d,e";   // String
txt.split(",");          // Split on commas
txt.split(" ");          // Split on spaces
txt.split("|");          // Split on pipe
Try it now

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

var txt = "Hello";       // String
txt.split("");           // Split in characters
Try it now



Practice Excercise Practice now

How To Recognize An Array

A common question is: How do I know if a variable is an array?

The problem is that the JavaScript operator typeof returns "object":

var fruits = ["Banana", "Orange", "Apple", "Mango"];

typeof fruits;    // returns object
 

The typeof operator returns object because a JavaScript array is an object.

Solution 1:

To solve this problem ECMAScript 5 defines a new method Array.isArray():

Array.isArray(fruits);   // returns true
 

The problem with this solution is that ECMAScript 5 is not supported in older browsers.

Solution 2:

To solve this problem you can create your own isArray() function:

function isArray(x) {
  return x.constructor.toString().indexOf("Array") > -1;
}
 

The function above always returns true if the argument is an array.

Or more precisely: it returns true if the object prototype contains the word "Array".

Solution 3:

The instanceof operator returns true if an object is created by a given constructor:

var fruits = ["Banana", "Orange", "Apple", "Mango"];

fruits instanceof Array;   // returns true



Practice Excercise Practice now

Previous Next
COMPANY
  • About us
  • Careers
  • Contact Us
  • In Press
  • People
  • Companies List
Products
  • Features
  • Coding Assessments
  • Psychometric Assessment
  • Aptitude Assessments
  • Tech/Functional Assessments
  • Video Assessment
  • Fluency Assessment
  • Campus
 
  • Learning
  • Campus Recruitment
  • Lateral Recruitment
  • Enterprise
  • Education
  • K 12
  • Government
OTHERS
  • Blog
  • Terms of Services
  • Privacy Policy
  • Refund Policy
  • Mart Category
Partner
  • Partner Login
  • Partner Signup

Copyright © RVR Innovations LLP 2025 | All rights reserved - Mytat.co is the venture of RVR Innovations LLP