techStackGuru

JavaScript String Methods


The JavaScript string is a character sequence that is represented as an object. A string can be any combination of letters, integers, special characters, and arithmetic values.

Ways to create string

  • By string literal
  • By string object

By string literal

Double quotes are used to build the string literal. Lets take an example

var val="Example string literal";  
console.log(val);  // Example string literal

By string object

We use new keyword for creating string object

var val = new String("Example string object");  
console.log(val); // Example string object

MethodDescriptionExample
charAt()It returns the char value found at the given index.

var str="aura";  
console.log(str.charAt(2));
//output r
concat()This method is used to combine two or more arrays.

var str1="android ";  
var str2="aura";  
var str3=str1.concat(str2);
console.log(str3);
//output android aura
indexOf()This method returns either -1 if an element cannot be found or the first index in the array at which it can be located.

var str1="Hello android aura";  
var str2=str1.indexOf("android");  
console.log(str2);
//output 6
lastIndexOf()This method returns either -1 if an element cannot be found or the last index in the array at which it can be located.

var str1="Hello android aura";  
var str2=str1.indexOf("aura");  
console.log(str2);
//output 14
toLowerCase()Converts strings into lowercase.

var str1="ANDROID";  
var str2=str1.toLowerCase(); 
console.log(str2);
//output android
toUpperCase()Converts strings into uppercase.

var str1="android";  
var str2=str1.toUpperCase(); 
console.log(str2);
//output ANDROID
slice(startIndex, endIndex)Used to extract specific portions of strings without changing the original strings

var str1="android";  
var str2=str1.slice(2,5);
console.log(str2);
//output dro
trim()Eliminates whitespace from strings both ends and produces a new string.

var str1=" android    ";  
var str2=str1.trim();
console.log(str2);
//output android
split()This method creates a list of substrings from a string and returns them in the form of an array.

var str1="hello android aura";  
var str2=str1.split(" ");
console.log(str2);
//output [ 'hello', 'android', 'aura' ]
replace()Finds the first instance of a string and replaces it with the provided string.

var str1 = "Hello World";
var str2 = str1.replace("World", "Android");
console.log(str2);
//output Hello Android
substr()The portion of the string between the start and end indexes is returned

var str1 = "Hello";
var str2 = str1.substr(1,3);
console.log(str2);
//output ell
valueOf()It returns primitive value.

var str1 = "Hello";
var str2 = str1.valueOf();
console.log(str2)
//output Hello

previous-button
next-button