Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var input = ' { Здоров | Даров | Привет | Прив | Ку } , %name%. { Как { дела | жизнь | оно } ? } ';
- // var input = ' { Здоров | Даров | Привет | Прив | Ку } , %name%. { Как { дела | жизнь | оно } ? | Что делаешь? | Покидай музыки на стену. | Поставь лойс на аву. } ';
- var i = 0, j = 0, l = input.length, output = '';
- function parseBraces() {
- var arr = [], temp;
- while (++i < l) {
- if (input[i] == '{') {
- temp = input.slice(j, i);
- j = i + 1;
- arr.push( temp + parseBraces() );
- }
- else if (input[i] == '}') {
- arr.push( input.slice(j, i) );
- j = i++ + 1;
- alert( JSON.stringify(arr) );
- return arr[ Math.floor( Math.random() * arr.length ) ];
- }
- else if (input[i] == '|') {
- arr.push( input.slice(j, i) );
- j = i + 1;
- }
- }
- throw Error('unexpected end');
- }
- while (i < l) {
- if (input[i] == '{') {
- alert( i )
- output += input.slice(j, i);
- j = i + 1;
- output += parseBraces();
- }
- else if (input[i] == '}') {
- throw Error('unexpected }');
- }
- ++i;
- }
- alert( output + input.slice(j, l) );
- // =======================================================================================================
- function prepareMessage(input, replacements) {
- return input.replace(/\{(.+?)\}/g, function(s, m) {
- m = m.split('|');
- return m[ Math.floor( Math.random() * m.length ) ];
- }).replace(/%(.+?)%/g, function(s, m) {
- return replacements[m] ? replacements[m] : s;
- });
- }
- alert( prepareMessage('{Даров|Прив|Ку}, %name%. {Как дела?|Что делаешь?| Покидай музыки на стену.|Поставь лойс на аву.}', {name: 'Иван'}) );
Advertisement
Add Comment
Please, Sign In to add comment