Recipe 3 | Matching the Beginning or End of a String with startsWith() and endsWith() |
Task
Let’s assume you have a database of articles about pet care and your task is to compile a list of questions that are answered in the articles. Suppose the articles are formatted in the Markdown language and the questions are all in level 2 heading tags (preceded with ##).
How would you write a code that distinguishes a heading from a normal sentence? And what would you use if you wanted to filter those that are questions? You need a solution that lets you check the characters at the beginning and end of a string.
Solution
First, we’ll use the startsWith() method to determine if the string begins with ##:
Get Text Processing with JavaScript now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.