JavaScript String Methods

Introduction

JavaScript String Methods help you to work with Strings. Here are various helper methods to work with a series of characters.

Note : All JavaScript String Methods return new a string. They do not change the original string.

JavaScript String Methods
JavaScript String Methods

Find String Length

The JavaScript length property returns the length of any string for example.

// Example

let myString = "This is a string";

let string_length =  myString.length;

console.log(string_length)
// output 16

Finding a specific text

The indexOf() method

 This method returns the position of the first occurrence of a specified text in a string.

Note: JavaScript always counts from zero.

Below the example shows the position of “JavaScript”.

// Example, indexOf()

let my_string = "I am learning JavaScript";
let str_position = my_string.indexOf("JavaScript");

console.log(str_position);

//output  14

If The string not found then it returns -1

// Example, if string not found.

let my_string = "I am learning JavaScript";
let str_position = my_string.indexOf("C Language");

console.log(str_position);

//output  -1

The lastIndexOf() method

This method returns the position of the last occurrence of a specified text in a string. It returns -1 if the specified text not found.

The example shows the position of “JavaScript”.

//Example, lastIndexOf()

let my_string = "we are learning JavaScript language, and JavaScript is easy to understand";

let str_position = my_string.lastIndexOf('JavaScript');

console.log(str_position);

//output 41

Parameters of indexOf() & lastIndexOf() methods.

The indexOf() and lastIndexOf() method accepts 2nd parameter as starting position for search.

They both search the specified text from this given position.

The basic difference between these two methods is the lastIndexOf() method search from end to beginning (backward search) but the indexOf() method search is forward.

Searching for a specific text

JavaScript String Methods
JavaScript String Methods (searching)

search() method

With the help of the search() method, you can search the position of a specified value and get the position.

This method is used to search for a match between a regular expression and a specified string.

//Example 
// javascript string methods

let my_str = "we are learning JavaScript language.";
let str_position = my_str.search("learning");
console.log(str_position);

//output  7

// 

How the two methods, indexOf() and search(), are not equal?

These methods are not equal because The search() method does not accept the second argument as a start position.

The indexOf() method cannot search for values on the basis of regular expressions.

Extract Part of a String

The JavaScript provides three methods to extract the part of a string.

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

slice() method

This method accepts 2 parameters. The starting position and the ending position.

The ending position is not included. Consider the following example.

// example 
// javascript string methods

let str = "red, blue, green";
let str_part = str.slice(4, 9);
console.log(str_part);

//output blue

//

JavaScript counts from zero.

If the parameters are negative Eg. slice(-13, -6) then the position is counted from the ending of the string or given value.

//example of negative values (print blue)
// javascript string methods

let str = "red, blue, green";
let str_part = str.slice(-12, -7);
console.log(str_part);

//output blue

//

The slice() method return rest of the string if you omit the second parameter.

//example
// javascript string methods

let str = "red, blue, green";
let str_part = str.slice(4);
console.log(str_part);

//output blue, green

//

If you provide negative parameter it counts from ending and gives output as

//example
// javascript string methods

let str = "red, blue, green";
let str_part = str.slice(-6);
console.log(str_part);

//output  green

//

JavaScript substring() method.

The substring accepts two parameters. It will give same output as slice method.

unlike the slice method the substring method cannot accept the negative number as parameter.

//example

let str = "red, blue, green";
let str_part = str.substring(0,3);
console.log(str_part);

//output  red

//

JavaScript substr() Method

The substr() method is also similar to slice method, but the second parameter shows the length of string.

The output willbe similar to substring() method.

String replace() method

The replace method replace the specified value.

We are replacing the “sentence” with “paragraph”.

The replace() method is case sensitive. If you want to replace uppercase with lower case then you need to use regular expression with a flag as

srting.replace('/sentence/i', 'paragraph');

The  /i  flag is used for insensitivity. Now the above code can replace ‘SENTENCE’ as well.

To replace all mtches use the global match flag with regular expression   /g 

//example

  var text = "This is a sentence"; 
  var txt = text.replace("sentence","paragraph");
  console.log(txt);

//output: This is a paragraph

//

Converting the string to upper and lower case using javascript string methods

toUpperCase() method.

The toUpperCase() method converts string to upper case.

//Example

var txt1 = "Some Text Here";
var txt2 = txt1.toUpperCase();
console.log(txt2);

//Output: SOME TEXT HERE

//

toLowerCase() Method

The toLowerCase() methode converts the string to lower case.

//Example

var txt1 = "SOME TEXT HERE";
var txt2 = txt1.toLowerCase();
console.log(txt2);

//Output: some text here

//

Join two strings into one using javascript string methods

concat() method

The concat() method works same as the ( + ) operator in Javascript.

It join two strings.

The first parameter is separater. you can specify space hyphen etc.

//example


var txt1 = "TEXT ONE";
var txt2 = "text two";
var txt3 = txt1.concat(' ', txt2);
console.log(txt3);

// output: TEXT ONE text two

//

Remove White Space Using trim() method

The trim method removes white space from both side of string. consider the following example.

//Example of js trim() method


var str_with_whitespaces = "   Hello World   ";
let trim_str = str_with_whitespaces.trim();
console.log(trim_str);

// output: Helo World

Find a Character by position, using charAt() method

The chatAt(position) method returns the character at specified position. for example the in “Helo World” The character at ‘0’ is ‘H’.

//Example

let str = "Helo World";
let firstChar = str.charAt(0);
console.log(firstChar);

// output: H

Find unicode of specified character

The charCodeAt() returns the unicode value of a character at specified position in a string.

Note that this method returns a UTF-16 code (integer between 0 and 65535).

//Example

let str = "Helo World";
let firstCharCode = str.charCodeAt(0);
console.log(firstCharCode);

// output: 72

converting a string to an array

The split() method is used to split the given string into array of strings by separating it into substrings using a specified separator given in the argument.

This method accept a argument as separater. you can specify any separater for example,

// Example

var str = "one, two, three, four"; 

// split using comma as a separater
str.split(",");
//output: ["one", " two", " three", " four"]


 // Split using spaces
str.split(" "); 
//output:  ["one,", "two,", "three,", "four"]

// Split with pipe
str.split("|"); 
// the | sign is absent in the given string so you will get whole string as one element of array
//output: ["one, two, three, four"]   

//try it yourself, what if we set no separaters, as
str.split('')

// you can specify any separater

Learn more about JavaScript String Methods in Video

Learn JavaScript Map method with ES6 example code

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *