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

Leave A Reply

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

You May Also Like

You might want to filter an array in JavaScript by passing the filter criteria and return the filtered array. In...
You can flatten a 2-D array in JavaScript using the concat and apply method as shown in the below code...
Assume that you have an angle in degree and you wish to convert it to radians in JavaScript so that...