Last active
August 29, 2015 14:25
-
-
Save wadackel/7d89c7bc69f90acebd06 to your computer and use it in GitHub Desktop.
シンプルなtemplate関数2種類
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
| /** | |
| * ================================================ | |
| * シンプルに | |
| * ================================================ | |
| */ | |
| /** | |
| * テンプレート文字列を展開 | |
| * | |
| * @param string:String テンプレート文字列 | |
| * @param values:Object 展開する値 | |
| * @return String | |
| */ | |
| function template(string, values){ | |
| return string.replace(/\$\{(.*?)\}/g, function(all, key){ | |
| return Object.prototype.hasOwnProperty.call(values, key) ? values[key] : ""; | |
| }); | |
| } | |
| // test | |
| console.log(template("My name is ${name} ${hoge}", {name: "Bob"})); // => My name is Bob | |
| /** | |
| * ================================================ | |
| * 形式を指定出来るように | |
| * ================================================ | |
| */ | |
| /** | |
| * 文字列を正規表現用にエスケープ | |
| * @see http://phpjs.org/functions/preg_quote/ | |
| */ | |
| function preg_quote(str, delimiter) { | |
| return String(str).replace(new RegExp('[.\\\\+*?\\[\\^\\]$(){}=!<>|:\\' + (delimiter || '') + '-]', 'g'), '\\$&'); | |
| } | |
| /** | |
| * テンプレート文字列を展開 | |
| * | |
| * @param string:String テンプレート文字列 | |
| * @param values:Object 展開する値 | |
| * @param before:String("${") テンプレートの開始文字 | |
| * @param after:String("}") 終了文字 | |
| * @return String | |
| */ | |
| function template(string, values, before, after){ | |
| before = preg_quote(before || "${"); | |
| after = preg_quote(after || "}"); | |
| return string.replace(new RegExp(before + "(.*?)" + after, "g"), function(all, key){ | |
| return Object.prototype.hasOwnProperty.call(values, key) ? values[key] : ""; | |
| }); | |
| } | |
| // test | |
| console.log(template("My name is ${name} ${hoge}", {name: "Bob"})); // => My name is Bob | |
| console.log(template("My name is %name% %hoge%", {name: "Bob"}, "%", "%")); // => My name is Bob |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment