Extract List from a String in JavaScript

Assume that you have a string that contains few statements out of which one includes the list of items. You may want to extract the list based on some delimitter.

Eg : The sentence contains the following ‘List of actors in Tamil Cinema: Vijay , Ajith , Suriya.’

We may need to extract the name of the actors Vijay , Ajth , Suriya from the sentence assuming that the list begins with colon and ends with a period.

How to extract a list from a string in JavaScript ?

Below is a sample code snippet demonstrating the usage of the indexof and split methods of the string to extract a list from a string in javascript.

<html>
<head>
    <script>
    var input = 'List of actors in Tamil Cinema: Vijay , Ajith , Suriya.';
    var startingIndex = input.indexOf(':');
    var endIndex = input.indexOf('.');
    var actorsStr = input.substring(startingIndex + 1, endIndex);
    var actorsList = actorsStr.split(',');
    document.write(actorsList);
    console.log(actorsList);
    </script>
</head>
<body>
</body>
</html>

image

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Hey, wait!Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.