56918

Match everything except a specific pattern in JavaScript

Question:

After much searching I am still stumped. How do I match everything in a string except what matches a given pattern.

I have found solutions for negating specific words or character sets using the ^ or negative look ahead, but I need a solution to negate anything that matches a specific pattern.

Example text (snippet of html):

abcd efg hijkl <span class='skipMe'>xxx</span> nop qrst uv wxyz.

I want to match everything except the whole span tag. i.e. everything except

/<span.*?<\/span>/

Any leads are appreciated.

Answer1:

You could always split your text on the regex like this:

<pre class="snippet-code-js lang-js prettyprint-override">var text = 'abcd efg hijkl <span class="skipMe">xxx</span> nop qrst uv wxyz.' console.log( text.split(/<span.*?<\/span>/) )

Answer2:

console.log('abcd efg hijkl <span class=\'skipMe\'>xxx</span> nop qrst uv wxyz.'.replace(/<(|\/)span[^>]*>/g, '')); //OR variant #2 console.log('abcd efg hijkl <span class=\'skipMe\'>xxx</span> nop qrst uv wxyz.'.replace(/\s<span.+span>?/g, ''));

<a href="http://jsbin.com/hucosed/edit?js,console" rel="nofollow">SEE</a>

Answer3:

Using regular expressions in this way is extremely naive and prone to unwanted side-effects. My recommendation would be to use the built-in DOM API.

Create a wrapper element, set the value of the innerHTML property to the input string, query the wrapper element for the element in question, remove the element in question, then return the value of the innerHTML property.

Here's an example:

<pre class="snippet-code-js lang-js prettyprint-override">const input = "abcd efg hijkl <span class='skipMe'>xxx</span> nop qrst uv wxyz."; const func = input => { const wrapper = Object.assign(document.createElement('div'), { innerHTML: input }); wrapper.querySelector('.skipMe').remove() return wrapper.innerHTML; }; console.log(func(input));

One caveat of this approach is that the HTML is passed to the parser, so if the HTML is not valid, <a href="https://locuststreetpress.files.wordpress.com/2013/09/super-creeper-bunny-meme-generator-scary-things-will-happen-if-you-don-t-follow-the-rules-0e0681.jpg" rel="nofollow">scary things will happen</a>

Recommend

  • Show xticks which are function of x-axis, not directly the data it self. Example with dates (pandas,
  • Facing issue in running multiple emulators with AOSP
  • How to add the new JSON from existing JSON file
  • Reorder dictionary in python according to a list of values
  • Migrating to CursorLoader & LoaderManager for AutoCompleteTextView with SQLiteDatabase
  • RSRuntimeException: Loading of ScriptC script failed (build tools 19.0.2)
  • Escape awk special character in Python
  • How can I progmatically click a link in a Winform Web Browser control?
  • Counting the Words in a String [closed]
  • Tensorflow converging but bad predictions
  • Implementing type equation generator in OCaml
  • Battery life if using GPS and background app ios/android
  • VB.net Service Programming and using TCP Sockets
  • Videos won't upload
  • How to modify the way a ForeignKey field is rendered in a Django admin page to avoid browser crash?
  • In metro, get all inherited classes of an (abstract) class?
  • Scheme procedure to compute the nth repeated application of a function?
  • Update all WooCommerce product prices to 2 decimals in database
  • Checking for valid enum types from protobufs
  • Fortran function variable length string return
  • separate tokens in batch file
  • Arraylist of strings into one comma separated string
  • Spotify cocoalibspotify offline status set to 1 but all tracks stuck at waiting
  • How do I use libcurl to printf a remote FTP directory listing?
  • Multiplying polynomials/simplifying like terms
  • Floating parent div grows to hypothetical width of floating child div
  • Send array to next viewcontroller iOs xcode [duplicate]
  • How to get rgb from transparent pixel in js
  • Codeigniniter insert data through models and controller
  • How to use FirstOrDefault inside Include
  • PHP Permalinks.. how to change?
  • media foundation H264 decoder not working properly
  • Running R's aov() mixed effects model from Python using rpy2
  • What does the “id” field in an Android “Google Play Music” broadcast intent correspond to?
  • Access to a Matlab gui from the web
  • ReferenceError: TextEncoder is not defined