Skip to content

Instantly share code, notes, and snippets.

@asm-jaime
Created May 27, 2017 20:26
Show Gist options
  • Save asm-jaime/7a7971faf0517ecac6a66f354e540fe0 to your computer and use it in GitHub Desktop.
Save asm-jaime/7a7971faf0517ecac6a66f354e540fe0 to your computer and use it in GitHub Desktop.
get all tags from a text (javascript), '#dfgdgf fgsdfg fgfgfgfg #gg' to ['#dfgdgf', '#gg'].
function get_tags(text) { //{{{
console.time('algs tags time');
const tags = [];
const txt = text.trim().split('');
let reg_tag = false;
let cur_tag = '';
for (let i = 0; i < txt.length; i++) {
if (reg_tag && txt[i] === '#') {
tags.push(cur_tag);
cur_tag = '';
};
if (!reg_tag && txt[i] === '#') {
reg_tag = true;
};
if (reg_tag && txt[i] === ' ') {
if (cur_tag !== '#') {
tags.push(cur_tag);
}
reg_tag = false;
cur_tag = '';
continue;
};
if (reg_tag) {
cur_tag = cur_tag + txt[i];
};
};
tags.push(cur_tag);
console.timeEnd('algs tags time');
return tags;
} //}}}
function get_regular_tags(text) { //{{{
console.time("regular time");
const regex = /\#(\w+)/g;
const tags = [];
let m;
while (m = regex.exec(text)) {
tags.push(m[1]);
}
console.timeEnd("regular time");
return tags;
} //}}}
const t1_txt = '#cg#dfg fgfg# #dfdf'; //{{{
const t2_txt = '#cg#dfg # dsdfg 32gf #dsfa df s# dsgf sfdg fsg dfdfdfdf # dfgfsadgfdsg #dsfagsadfg # dsagasgfg #dfasfdasdfdsfasdgfafgafsdg#### sa#dfsdf#fgfg# #dfd ## sadfg G#dsgf ##$DFASDGfscgvsagsdfg#@#$$## fdsgfgasd### #RSDFAWDSF#43334##EFDFGSadf 34$## dasdgfasdfg#DFdfsgasdfdf#adgf'; //}}}
console.log(t1_txt);
console.log(get_tags(t1_txt));
console.assert(get_tags(t1_txt).length === get_regular_tags(t1_txt).length, 'bad len');
console.log(get_tags(t2_txt).length);
console.log(get_regular_tags(t2_txt).length);
console.assert(get_tags(t2_txt).length === get_regular_tags(t2_txt).length, 'bad len');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment