Created
March 17, 2017 10:31
-
-
Save magician11/ddb7828ddf0a48d3fa9efa06f3a35b92 to your computer and use it in GitHub Desktop.
How to use variables in regular expressions in JavaScript.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A video walkthrough is available here: https://youtu.be/9BVw7OOdqU4