Skip to content

Instantly share code, notes, and snippets.

@ronaiza-cardoso
Last active August 28, 2018 09:14
Show Gist options
  • Save ronaiza-cardoso/b0cdcdef0e3516a0fd88c78832c387f9 to your computer and use it in GitHub Desktop.
Save ronaiza-cardoso/b0cdcdef0e3516a0fd88c78832c387f9 to your computer and use it in GitHub Desktop.
export class StringUtil {
// How to use it:
// import { StringUtil } from 'utils/string-search';
//
// objToSearch.filter((name) => {
// return StringUtil.stringRegExp(searchTerm, false).test(name);
// });
static stringRegExp(text: string, isGroup: boolean = true): RegExp {
let RegexSearchTerm,
RegExMap,
term = '';
RegExMap = {
'A': '[AÀÁÂÃÄÅ]',
'À': '[AÀÁÂÃÄÅ]',
'Á': '[AÀÁÂÃÄÅ]',
'Â': '[AÀÁÂÃÄÅ]',
'Ã': '[AÀÁÂÃÄÅ]',
'Å': '[AÀÁÂÃÄÅ]',
'E': '[EÉÈÊẼË]',
'É': '[EÉÈÊẼË]',
'È': '[EÉÈÊẼË]',
'Ê': '[EÉÈÊẼË]',
'Ẽ': '[EÉÈÊẼË]',
'Ë': '[EÉÈÊẼË]',
'I': '[IÌÍÏĨÎ]',
'Ì': '[IÌÍÏĨÎ]',
'Í': '[IÌÍÏĨÎ]',
'Ï': '[IÌÍÏĨÎ]',
'Ĩ': '[IÌÍÏĨÎ]',
'Î': '[IÌÍÏĨÎ]',
'O': '[OÒÓÕÔÖ]',
'Ö': '[OÒÓÕÔÖ]',
'Ò': '[OÒÓÕÔÖ]',
'Ó': '[OÒÓÕÔÖ]',
'Õ': '[OÒÓÕÔÖ]',
'Ô': '[OÒÓÕÔÖ]',
'U': '[UÙÚÜÛŨ]',
'Ù': '[UÙÚÜÛŨ]',
'Ú': '[UÙÚÜÛŨ]',
'Ü': '[UÙÚÜÛŨ]',
'Û': '[UÙÚÜÛŨ]',
'Ũ': '[UÙÚÜÛŨ]',
'C': '[CÇ]',
'Ç': '[CÇ]',
'N': '[NÑ]',
'Ñ': '[NÑ]',
'(': '\\(',
')': '\\)',
'[': '\\[',
']': '\\]'
};
RegexSearchTerm = text.toUpperCase();
for (let i = 0, len = RegexSearchTerm.length; len--; i += 1) {
let charItem = RegexSearchTerm.charAt(i);
term += (charItem in RegExMap) ? RegExMap[charItem] : charItem;
}
term = (isGroup) ? `(${term})` : term;
return new RegExp(term, 'gi');
}
/**
* http://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript-jquery
* @param value
* @returns {number}
*/
static hashCode(value: string) {
let hash = 0, i, chr, len;
if (value.length === 0) return hash;
for (i = 0, len = value.length; i < len; i++) {
chr = value.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment