Tutorial Strip Whitespace From String

by in , 0

Whitespace, meaning tabs and spaces.

// Remove leading and trailing whitespace
// Requires jQuery
var str = " a b    c d e f g ";
var newStr = $.trim(str);
// "a b c d e f g"

// Remove leading and trailing whitespace
// JavaScript RegEx
var str = "   a b    c d e f g ";
var newStr = str.replace(/(^\s+|\s+$)/g,'');
// "a b c d e f g"

// Remove all whitespace
// JavaScript RegEx
var str = " a b    c d e   f g   ";
var newStr = str.replace(/\s+/g, '');
// "abcdefg"

Doesn't work with other types of whitespace though, for instance   (thin space) or   (non-breaking space)

Tutorial Strip Numbers from a String

by in , 0

var someString = "Hello 123 World!";

newString = someString.replace(/[0-9]/g, '');

// console.log(newString);
// "Hello  World!";

Tutorial Strip HTML Tags in JavaScript

by in , 0

var StrippedString = OriginalString.replace(/(<([^>]+)>)/ig,"");

Tutorial Shuffle Array

by in , 0

Technique #1

function Shuffle(o) {
	for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
	return o;
};

Usage

var testArray = [1,2,3,4,5];
Shuffle(testArray);

// jQuery to dump out new values to element with ID of 'dump'
$(function() {
   for (var i=0;i<testArray.length;i++) {
      $("#dump").append(testArray[i]);
   }
});

Technique #2

yourArray.sort(function() { return 0.5 - Math.random() });

Tutorial Saving contenteditable Content Changes as JSON with Ajax

by in , 0

Elements with the contenteditable attribute can be live-edited right in the browser window. But of course those changes don't affect the actual document on your server, so those changes don't persist with a page refresh.

One way to save the data would be to wait for the return key to be pressed, which triggers then sends the new innerHTML of the element as an Ajax call and blurs the element. Pressing escape returns the element to it's pre-edited state.

document.addEventListener('keydown', function (event) {
  var esc = event.which == 27,
      nl = event.which == 13,
      el = event.target,
      input = el.nodeName != 'INPUT' && el.nodeName != 'TEXTAREA',
      data = {};

  if (input) {
    if (esc) {
      // restore state
      document.execCommand('undo');
      el.blur();
    } else if (nl) {
      // save
      data[el.getAttribute('data-name')] = el.innerHTML;

      // we could send an ajax request to update the field
      /*
      $.ajax({
        url: window.location.toString(),
        data: data,
        type: 'post'
      });
      */
      log(JSON.stringify(data));

      el.blur();
      event.preventDefault();
    }
  }
}, true);

function log(s) {
  document.getElementById('debug').innerHTML = 'value changed to: ' + s;
}

Live demo on JS Bin by Remy Sharp.

Tutorial Remove the Last Character from a String

by in , 0

var origString = 'Happy Dance7';
var trimmedString = origString.substring(0, origString.length-1);
console.log(trimmedString);
// 'Happy Dance'

Tutorial Remove Inline Styles

by in , 0

This function also preserves hidden content.

function remove_style(all) {
  var i = all.length;
  var j, is_hidden;

  // Presentational attributes.
  var attr = [
    'align',
    'background',
    'bgcolor',
    'border',
    'cellpadding',
    'cellspacing',
    'color',
    'face',
    'height',
    'hspace',
    'marginheight',
    'marginwidth',
    'noshade',
    'nowrap',
    'valign',
    'vspace',
    'width',
    'vlink',
    'alink',
    'text',
    'link',
    'frame',
    'frameborder',
    'clear',
    'scrolling',
    'style'
  ];

  var attr_len = attr.length;

  while (i--) {
    is_hidden = (all[i].style.display === 'none');

    j = attr_len;

    while (j--) {
      all[i].removeAttribute(attr[j]);
    }

    // Re-hide display:none elements,
    // so they can be toggled via JS.
    if (is_hidden) {
      all[i].style.display = 'none';
      is_hidden = false;
    }
  }
}

Usage

Call the function like this:

var all = document.getElementsByTagName('*');
remove_style(all);

Note: Selecting all elements in the page via a wildcard query could be slow, depending on how many elements are in the page. You could use a smaller set of elements to be more performant:

var set = document.getElementById('foo').getElementsByTagName('bar');
remove_style(set);

Code by Nathan Smith.