How to get a part of string after a specified character in JavaScript?


To get a part of a string, string.substring() method is used in javascript. Using this method we can get any part of a string that is before or after a particular character.

str.substring() 

This method slices a string from a given start index(including) to end index(excluding). If only one index is provided then the method slice the entire string from the start of the index. 

syntax-1

Using this line of code we can get a part of a string after a particular character.

string.substring(string.indexOf(character) + 1);

syntax-2

Using this line of code we can get a part of a string before a particular character.

string.substring(0, string.indexOf(character));

Example

Live Demo

<html>
<body>
<script>
   function subStr(string, character, position) {
      if(position=='b')
      return string.substring(string.indexOf(character) + 1);
      else if(position=='a')
      return string.substring(0, string.indexOf(character));
      else
      return string;
   }
   document.write(subStr('Tutorix & Tutorialspoint','&','a'));
   document.write("</br>");
   document.write(subStr('Tutorix:a best e-learning platform', ':','b'));
</script>
</body>
</html>

Output

Tutorix
a best e-learning platform
raja
Published on 18-Jun-2019 15:24:21
Advertisements