wp-sanitize.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /**
  2. * @output wp-includes/js/wp-sanitize.js
  3. */
  4. ( function () {
  5. window.wp = window.wp || {};
  6. /**
  7. * wp.sanitize
  8. *
  9. * Helper functions to sanitize strings.
  10. */
  11. wp.sanitize = {
  12. /**
  13. * Strip HTML tags.
  14. *
  15. * @param {string} text Text to have the HTML tags striped out of.
  16. *
  17. * @return Stripped text.
  18. */
  19. stripTags: function( text ) {
  20. text = text || '';
  21. // Do the replacement.
  22. var _text = text
  23. .replace( /<!--[\s\S]*?(-->|$)/g, '' )
  24. .replace( /<(script|style)[^>]*>[\s\S]*?(<\/\1>|$)/ig, '' )
  25. .replace( /<\/?[a-z][\s\S]*?(>|$)/ig, '' );
  26. // If the initial text is not equal to the modified text,
  27. // do the search-replace again, until there is nothing to be replaced.
  28. if ( _text !== text ) {
  29. return wp.sanitize.stripTags( _text );
  30. }
  31. // Return the text with stripped tags.
  32. return _text;
  33. },
  34. /**
  35. * Strip HTML tags and convert HTML entities.
  36. *
  37. * @param {string} text Text to strip tags and convert HTML entities.
  38. *
  39. * @return Sanitized text. False on failure.
  40. */
  41. stripTagsAndEncodeText: function( text ) {
  42. var _text = wp.sanitize.stripTags( text ),
  43. textarea = document.createElement( 'textarea' );
  44. try {
  45. textarea.textContent = _text;
  46. _text = wp.sanitize.stripTags( textarea.value );
  47. } catch ( er ) {}
  48. return _text;
  49. }
  50. };
  51. }() );