Turn camelCaseWords from data attribute into "Camel Case Words"

javascript, jquery

Solution

$('a').click(function() {
    var str = $(this).data('test'); // get the concated string
    var arr = str.split(""); // Convert the string to array
    for (var i = arr.length - 1; i >= 0; i--) {  // iterate over the characters 
        if (arr[i].match(/[A-Z]/))  // if the char is uppercase
            arr.splice(i, 0, " "); // add a space before it
    }

    arr[0] = arr[0].toUpperCase();    // upper the first char.
    var splitedString = arr.join(""); // convert the array to string
    alert(splitedString); // alert the string.
});​

LIVE DEMO

Problem

I have a set of links with custom HTML5 data attributes like this one: `data-test="justExample"` ``` <a href="#" data-test="somethingSpecial"> This should output "Something Special" </a> ``` I want to return this value as `"Just Example"` instead of "`justExample"`. Feel free to edit this jsfiddle I created.

Original source