JavaScript Tutorial – String Methods

String methods are very handy when you need to work with strings.

How to find text in a String

indexOf() returns the first index position of the first occurrence of specified text in a string.

Example of indexOf

<script type="text/javascript">
   var website = "What html";
   var pos = website.indexOf("a");
</script>
Try it yourself »

Above JavaScript will return index of 2. In JavaScript, index starts at 0, from left to right. So in the above example, W is at index 0, h is at index 1, and a is at index 2.

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

Example of lastIndexOf()

<script type="text/javascript">
   var website = "What html";
   var pos = website.lastIndexOf("t");
</script>
Try it yourself »

Above JavaScript will return index of 6. This is because this string contains t at index 3 and 6.

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

How To search for text in a String

The search() method searches a string for a specified value and returns the position of the match. indexOf() and search() are every similar except that search() can search for much complex texts.

<script type="text/javascript">
   var website = "What html";
   var pos = website.search("a");
</script>
Try it yourself »

How to extract part of String

substring() returns part of a string. The method takes 2 parameters: the starting index (position), and the ending index (position).

substring() Example

<script type="text/javascript">
   var website = "WhatAboutHTML";
   //start from index 2 and end at index 5
   var str = website.substring(2,5);
</script>
Try it yourself »

How to replace String

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

<script type="text/javascript">
   var website = "WhatAboutHTML";
   var str = website .replace("About"," Is ");
</script>
Try it yourself »

How to convert string to upper case

toUpperCase() converts any string to upper case.

toUpperCase() Example

<script type="text/javascript">
   var website = "WhatAboutHTML";
   var website1 = website.toUpperCase();
</script>
Try it yourself »

How to convert string to lower case

toLowerCase() converts any string to lower case.

toLowerCase() Example

<script type="text/javascript">
   var website = "WhatAboutHTML";
   var website1 = website.toLowerCase();
</script>
Try it yourself »