-2

I have a variable which contains this:

var a = "hotelRoomNumber";

Is there a way I can create a new variable from this that contains: "Hotel Room Number" ? I need to do a split on the uppercase character but I've not seen this done anywhere before.

dmullings
  • 7,070
  • 5
  • 28
  • 28
Samantha J T Star
  • 30,952
  • 84
  • 245
  • 427

3 Answers3

2

Well, you could use a regex, but it's simpler just to build a new string:

var a = "hotelRoomNumber";
var b = '';
if (a.length > 0) {
    b += a[0].toUpperCase();
    for (var i = 1; i != a.length; ++i) {
        b += a[i] === a[i].toUpperCase() ? ' ' + a[i] : a[i];
    }
}

// Now b === "Hotel Room Number"
Cameron
  • 96,106
  • 25
  • 196
  • 225
1

I have made a function here:

http://jsfiddle.net/wZf6Z/2/

function camelToSpaceSeperated(string)
{
    var char, i, spaceSeperated = '';

    // iterate through each char
    for (i = 0; i < string.length; i++) {
        char = string.charAt(i); // current char

        if (i > 0 && char === char.toUpperCase()) { // if is uppercase
            spaceSeperated += ' ' + char;
        } else {
            spaceSeperated += char;
        }
    }

    // Make the first char uppercase
    spaceSeperated = spaceSeperated.charAt(0).toUpperCase() + spaceSeperated.substr(1);

    return spaceSeperated;
}

The general idea is to iterate through each char in the string, check if the current char is already uppercased, if so then prepend a space to it.

Chris Lam
  • 3,526
  • 13
  • 10
  • extraneous space at beginning of string. "A" becomes " A". – djechlin Jul 13 '14 at 04:39
  • thanks djechlin for pointing this out. Checking if it is the first char in the if condition or simply trimming the string before returning can do the trick. – Chris Lam Jul 13 '14 at 04:43
1
var str = "mySampleString";
str = str.replace(/([A-Z])/g, ' $1').replace(/^./, function(str){ return str.toUpperCase(); });

http://jsfiddle.net/PrashantJ/zX8RL/1/

PrashantJ
  • 447
  • 1
  • 3
  • 9