Created
August 22, 2014 07:44
-
-
Save cladera/6fba66c0ec652edd6c0e to your computer and use it in GitHub Desktop.
URL Tag replace
This file contains hidden or 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
/* User data sample */ | |
var user = { | |
uid: 5678, | |
email: '[email protected]' | |
}; | |
/* Tag separator: *| */ | |
/* g modiffier is mandatory */ | |
var pattern = /\*\|([a-zA-Z0-9_]+)\|\*/g; | |
var url = 'http://www.acme.com/tnt/buy/?user=*|UID|*&email=*|EMAIL|*&size=*|SIZE|*'; | |
var result; | |
var results = []; | |
/*Iterate all results*/ | |
while((result = pattern.exec(url)) !== null){ | |
if(result.index === pattern.lastIndex){ | |
pattern.lastIndex++; | |
} | |
//Save all match and group match | |
results.push({ | |
tag: result[0], | |
variable: result[1] | |
}); | |
} | |
for(var i = 0; i < results.length; i++){ | |
var tag = results[i].tag; | |
var variable = results[i].variable; | |
//Find tag within URL and replace it by variable value | |
if(user[variable.toLowerCase()]){ | |
url = url.replace(tag, user[variable.toLowerCase()]); | |
} | |
} | |
console.log(url); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment