Return a String Between 2 Strings


/ Published in: JavaScript
Save to your folder(s)

//Takes 3 params
//1) inString: string to search
//2) inThis: aka find this / the starting text
//3) inThat: the ending string.
//For example: myBetween("the cow jumped over the moon", "cow", "moon")
//will return " jumped over the "


Copy this code and paste it in your HTML
  1. //Takes 3 params
  2. //1) inString: string to search
  3. //2) inThis: aka find this / the starting text
  4. //3) inThat: the ending string.
  5. //For example: myBetween("the cow jumped over the moon", "cow", "moon")
  6. //will return " jumped over the "
  7. function myBetween(inString, inThis, inThat)
  8. {
  9. var sResult = null; //return string
  10. try
  11. {
  12. var inThisPos = inString.indexOf(inThis); //check if 'inThis' is found in 'inString'
  13. if (inThisPos > -1) //yes there's a match
  14. {
  15. var inThatPos = inString.indexOf(inThat, (inThisPos + inThis.length) + 1); //find the 'inThat'
  16. if (inThatPos > inThisPos) //was it past the start of inThis
  17. {
  18. sResult = inString.substr(inThisPos + inThis.length, inThatPos - (inThisPos + inThis.length));
  19. }
  20. }
  21. }
  22. catch(err)
  23. {
  24. console.log("[myBetween()] Error: " + err.message);
  25. }
  26. return sResult;
  27. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.