Skip to content

Instantly share code, notes, and snippets.

@magician11
Created March 17, 2017 10:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save magician11/ddb7828ddf0a48d3fa9efa06f3a35b92 to your computer and use it in GitHub Desktop.
Save magician11/ddb7828ddf0a48d3fa9efa06f3a35b92 to your computer and use it in GitHub Desktop.
How to use variables in regular expressions in JavaScript.
function getURL(startMatch, endMatch, str) {
var regex = new RegExp(startMatch + ': (.+), ' + endMatch);
var contents = str.split(regex)[1];
return contents ? contents : 'none found';
}
var str = 'website: http://www.google.com, soundcloud: http://www.soundcloud.com, facebook: http://www.facebook.com, stage: the main one';
console.log('Website URL:', getURL('website', 'soundcloud', str));
console.log('Soundcloud URL:', getURL('soundcloud', 'facebook', str));
console.log('Facebook URL:', getURL('facebook', 'stage', str));
console.log('Another URL:', getURL('this', 'that', str));
@magician11
Copy link
Author

A video walkthrough is available here: https://youtu.be/9BVw7OOdqU4

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment