Last active
December 1, 2016 10:42
-
-
Save dmitrykuznetsovdev/2e513f84af11cc472d396005a93e5920 to your computer and use it in GitHub Desktop.
Find and replace in template
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 data | |
* @returns {string} | |
*/ | |
let myTemplate = function(data){ | |
let text = ` | |
If you are {full_name} a value (and not a regular expression), | |
only the first {name} of the value will be replaced. | |
To replace all occurrences of a specified value, use the global (g) modifier (see "More Examples" below). | |
Read more about regular expressions in our {text} Tutorial and our RegExp Object Reference. | |
This method does not change the original string {deep.deepProp}. | |
`; | |
let reg = /\{(.+)\}/ig; | |
let test = text.replace(reg, function(str, find, offset, s) { | |
if(find) { | |
return deeps(data, find); | |
} | |
}); | |
return text; | |
} | |
function deeps(obj, val) { | |
var hs = val.split('.'); | |
var len = hs.length; | |
var deep; | |
var num = 0; | |
for (var i = 0; i < len; i++) { | |
var el = hs[i]; | |
if (deep) { | |
if (deep[el]) { | |
deep = deep[el]; | |
num++; | |
} | |
} else { | |
if (obj[el]) { | |
deep = obj[el]; | |
num++; | |
} | |
} | |
} | |
if (num == len) { | |
return deep; | |
} else { | |
return undefined; | |
} | |
} | |
myTemplate({ | |
name: 'Дмитрий', | |
full_name: 'Дмитрий Димитрий', | |
text: 'что то', | |
deep: { | |
deepProp: 'deepProp 111' | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment