Skip to content

Instantly share code, notes, and snippets.

@CodingBobby
Created April 12, 2018 20:00
Show Gist options
  • Save CodingBobby/c5dd13a106b214304077b8fc19e2c41f to your computer and use it in GitHub Desktop.
Save CodingBobby/c5dd13a106b214304077b8fc19e2c41f to your computer and use it in GitHub Desktop.
Basically a function which takes a string and gives back an array of all consisted words, takes numbers and underscores into account
//
// Made by Bob Walter in 2k18
// Version 1.2.0
//
// ––– INPUT ––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– //
// input string
let str = "8fOo Bar8 fOo8bar fOo-Bar fOo_Bar 8.8 888 ,_?!";
// ––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– //
// regexps to filter words
const r1 = new RegExp(/[^\w]/,'g');
const r2 = new RegExp(/\b_|\b\d+(\s|$)/,'g');
// extending RegExp class, replaces input matches with spaces
class replaceWithSpaces extends RegExp {
[Symbol.replace](str) {
return RegExp.prototype[Symbol.replace].call(this, str, ' ');
}
}
// extending RegExp class, splits string at input and returns map of betweenies
class makeMap extends RegExp {
[Symbol.split](str, limit) {
var result = RegExp.prototype[Symbol.split].call(this, str, limit);
return result.map(x => x);
}
}
// extending Array class with function, removes input element from array and fills with remainings
Array.prototype.remove = function(from, to) {
var rest = this.slice((to || from) + 1 || this.length);
this.length = from < 0 ? this.length + from : from;
return this.push.apply(this, rest);
}
// function, takes and gives array, removes all emty elements and flatens content
function putWords(arr) {
for(var i = 0; i < arr.length; i++) {
if(arr[i] == "")
arr.remove(i--);
else
arr[i] = arr[i].toLowerCase();
}
return arr;
}
// function, takes string and gives array of consisted words
const wordsArr = (s) => {
return putWords(
s.replace(new replaceWithSpaces(r1)).replace(new replaceWithSpaces(r2)).split(new makeMap(' '))
);
}
// ––– OUTPUT –––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– //
let arr = wordsArr(str); // arr = ["8foo", "bar8", "foo8bar", "foo", "bar", "foo_bar"]
// ––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– //
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment