JavaScript String Methods

What is the String?

The string is a collection of one or more characters written inside quotes.

Example:

var m = “Erroser is the best website for learning”;

Note: We can use single quotes, too.

Example:

var n = ‘Errosea is love’;

JavaScript provides different string methods which help users to work with strings.

Different string methods are as follows

1) String Length method

This property returns the length of a string.

Example:

 var x = "Errorsea";
 var len = x.length;  // result: 8

2) The indexOf() Method

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

Example:

var x = "have you ever visit Errorsea";
var position =  x.indexOf("Errorsea");  // result: 20

Note: JavaScript counts positions form zero. It returns -1 if string not found in whole string.

3) The lastIndexOf() method

JavaScript provides lastIndexOf() method that returns the index of (the position of) the last occurrence of a specified text in a string:

Example:

var x = "Do visit Errosea because Errosea is the best learning platform";
var position =  x.lastIndexOf("Errorsea");  // result: 25

Note: JavaScript counts positions form zero. It returns -1 if string not found in whole string.

4) The slice() Method

This method extracts a particular part of a string and returns the extracted part as a new string.

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

Syntax:

slice(start, end)

Here,
start: start position
end: end position

Example 1:

var x = "HTML, CSS, JAVASCRIPT";
var result = x.slice(6,9);   // result: "CSS"

If we don’t write end position, then JS will take the end of a string as an end position.

Example 2:

var x = "HTML, CSS, JAVASCRIPT";
var result = x.slice(6);  // result: "CSS, JAVASCRIPT"

Note:

It will take the end of the string as an end position.

In case if a parameter is negative, the position is counted from the end of the string.

Example 3:

var x = "HTML, CSS, JAVASCRIPT";
var result = x.slice(-15,-12);   // result: "CSS"

Note:

It will count positions from the end of the string.

5) The substr() Method

This method extracts a particular part of a string and returns the extracted part as a new string.

Note:

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

Syntax:

substr(start, end)

Here,
start: start position
end: end position

Example:

var x = "HTML, CSS, JAVASCRIPT";
var result = x.substr(6,9);  // result: "CSS"

If we don’t write end position, then JS will take the end of the string as an end position.

Example:

var x = "HTML, CSS, JAVASCRIPT";
var result = x.substr(6);   // result: "CSS, JAVASCRIPT"

Note:

It will take the end of the string as an end position.

6) The replace() Method

The replace() function is used to replaces a specified value with another value in a string.

Example:

<!DOCTYPE html>
<html>
<body>

<h2>Errorsea - JavaScript String Methods</h2>

<p>Replace "facebook" with "Errorsea" in the paragraph below:</p>

<button onclick="rep()">replace</button>

<p id="demo">Do visit facebook !</p>

<script>
function rep() {
  var x = document.getElementById("demo").innerHTML; 
  var m = x.replace("facebook","Errorsea");
  document.getElementById("demo").innerHTML = txt;
}
</script>

</body>
</html>

Explanation:

The above code replaces facebook with Errorsea and places it inside the <p> tag.

Note: It replaces only first match string. This method is case sensitive.

7) The toUpperCase() method

We can convert the string into uppercase using toUpperCase() method.

Example:

var x = "Errorsea";
var upr = x.toUpperCase();   // result: "ERRORSEA"

8) The toLowerCase() method

We can convert the string into uppercase using toLowerCase() method.

Example:

var x = "Errorsea";
var lwr = x.toLowerCase();   // result: "errorsea"

9) The concat() Method

This method is used to join two or more strings.

Example:

var m = "Error";
var n = "sea";
var x = m.concat(n);   // result: "Errorsea"

Note: This method can be used instead of the plus operator.

Example:

var x = "Error" + "sea" ;

10) The trim() Method

This method removes whitespace from both sides of a string.

Example:

var x = "           Errorsea             ";
var trm = x.trim();    // result: "Errorsea"

Note: The trim() method of JS is not supported in Internet Explorer 8 or lower.

11) The charAt() Method

This method returns the character at a specified index (position) in a string.

Example:

var x = "Errorsea";
var ch = x.charAt(0);            // returns E

12) The charCodeAt() Method

This method returns the Unicode of the character at a specified index in a string.

Example:

var x = "Errorsea";
var code = x.charCodeAt(0);    //result : 69

13) Converting a String to an Array

In JS, a string can be converted to an array with the split() method. This method split the string and store it in the array.

Example:

<!DOCTYPE html>
<html>
<body>

<p>Click the button to display the first array element, after a string split.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {
  var x = "e,r,r,o,r,s,e,a";
  var arr = x.split(",");
  document.getElementById("demo").innerHTML = arr[0];
}
</script>

</body>
</html>

Explanation:

Above code split string contains in variable x using split() function and store it in the array. We show first element of array in innerHTML of <p> tag.

14) The endsWith() Method

This method determines whether a string ends with the characters of a specified string.

Example:

var x = "Errorsea is love"
var result = x.endsWith("love");  // result: true
var result2 = x.endsWith("hello");  // result: false

Note: It returns true if the string matches with the string at the end. It returns false if the string doesn’t match with the string at the end.

15) The fromCharCode() Method

This method converts Unicode values into characters.

Example:

var x = String.fromCharCode(69);  // result: "E"      

16) The includes() Method

This method determines whether a string contains the characters of a specified string.

Example:

var x = "Have you visit Errorsea";
var result = x.includes("Errorsea");  //result: true

Note: It returns true if the string contains characters of a specific string. It returns false if the string doesn’t contain characters of a specific string.

17) The localeCompare() Method

This method is used for comparing two strings in the current locale.

Example:

var str1 = "ab";
var str2 = "cd";
var x = str1.localCompare(str2);  // result : -1

Note:

  • Returns -1 if str1 is sorted before str2
  • Returns 0 as a result of the two strings are equal
  • Returns 1 if str1 is sorted after str2

18) The repeat() Method

This method returns a new string with a specified number of copies of the string it was called on.

Example:

<!DOCTYPE html>
<html>
<body>

<p>Click the button to display the extracted part of the string.</p>

<button onclick="rep()">Repeat</button>

<p id="demo"></p>

<script>
function rep() {
  var x = "Errorsea";
  document.getElementById("demo").innerHTML = x.repeat(2);
  //It returns two-time Errorsea as a result.
}
</script>

</body>
</html>

19) The search() Method

Javascript provides search() method that returns the index of a specified text in a string:

Example:

var x = "have you ever visit Errorsea";
var position =  x.search("Errorsea");  // result: 20

20) The startsWith() Method

This method is used to determines whether a string starts with the characters of a specified string.

Example:

var x = "Errorsea is love"
var result = x.startssWith("Errorsea");  // result: false
var result2 = x.startssWith("hello");  // result: true

Note: It returns true if the string matches with the string at the start. It returns false if the string doesn’t match with the string at the start.

21) The toLocaleUpperCase() method

We can convert the string into uppercase using toLocaleUpperCase() method according to the host’s current locale.

Example:

var x = "Errorsea";
var upr = x.toLocaleUpperCase();   // result: "ERRORSEA"

22) The toLocaleLowerCase() method

We can convert the string into uppercase using toLocaleLowerCase() method according to the host’s current locale.

Example:

var x = "Errorsea";
var lwr = x.toLocaleLowerCase();   // result: "errorsea"

23) The toString() Method

This method returns the value of a String object.

Example:

var x = 123;
var result = x.toString(); // result: string

Note: It converts the value of the variable to string.

24) The valueOf() Method

This method is used to returns the primitive value of a String object.

Example:

<!DOCTYPE html>
<html>
<body>

<p>Click the button to return the primitive value of the String object.</p>

<button onclick="myFun()">Click me</button>

<p id="demo"></p>

<script>
function myFun() {
  var x = "Errorsea";
  var result = x.valueOf();
  document.getElementById("demo").innerHTML = result;
}
</script>
</body>
</html>

Note: The valueOf() method is usually called automatically by JavaScript behind the scenes, and not explicitly in code.

Leave a Reply

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