Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I get a substring between a string and the first occurrence of another string?

My attempt so far:

const myString = 'Hello my name is Barbara but i dont really like the name Barbara I prefer Barb'

const mySubString = myString.substring(
   myString.indexOf("Hello") + 6,
   myString.lastIndexOf("Barbara")
);
console.log(mySubString)

this returns my name is Barbara but i dont really like the name, but I need my name is.

And I don’t see a firstIndexOf() method..

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Don’t use lastIndexOf if you want the first occurrence. indexOf gives the index of the first occurrence.

const myString = 'Hello my name is Barbara but i dont really like the name Barbara I prefer Barb'
const mySubString = myString.substring(
   myString.indexOf("Hello") + 6,
   myString.indexOf("Barbara") - 1
);
console.log('"' + mySubString + '"');
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading