Skip to content

Instantly share code, notes, and snippets.

@silicakes
Last active August 29, 2015 14:09
Show Gist options
  • Save silicakes/e110b807fea019ba9291 to your computer and use it in GitHub Desktop.
Save silicakes/e110b807fea019ba9291 to your computer and use it in GitHub Desktop.
Invert javascript regex
// sometimes it easier to select something constant rather than amorphic
// the following function allows the inversion of such regular expression
// while returning an array of the inverted matched results
//<regex> | object - the desired regular expression
//<str> | string - the string on which the manipulation will occur
//<clear> | boolean - whether should the return array be emptied out of empty cells: ["",1,2,""] -> [1,2]
function invertRegex(str, regex, clear) {
var arr = str.split(regex);
if(clear) {
arr = arr.filter(function(el) { return el.length > 0 });
}
return arr
}
//example
var str = '<div>something wicked <b>this way</b>comes<div><span class="caption" data-caption="wat">this is quite random</span></div></div>'
var re = /(<.*?>)/g; // matching all content within the <> tags
var invertedArray = invertRegex(str, re, true) // ["something wicked ", "this way", "comes", "this is quite random"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment