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

JavaScript supports different types of operators that includes Assignment Operator JavaScript supports different types if Assignment Operators like = +=...
Assume that you have an angle in degree and you wish to convert it to radians in JavaScript so that...
The JavaScript elements and statements are placed within the script tag within the HTML page. You can specify the language...