View Full Version : Capital letters

03-22-2008, 02:05 PM

is it possible to have JavaScript divide a word, based on Capital Letters.
Say the word "HelloWorld" is written into a file. JavaScript would then divide it into the two words "Hello World" ?

If it is possible, could you show me how.

Thank you, Marringi

03-22-2008, 04:18 PM
Try this:

var separated = "HelloWorld".replace(/(\S)([A-Z])/g, "$1 $2");

03-22-2008, 04:42 PM
Thank you for the answer. Could you also show me how you would use it with "document.write" ?

Thank you

03-23-2008, 02:23 AM
Document.write should only be used as the page is being loaded (parsed), otherwise it will overwrite the page, hopefully you understand this. Assuming that you do, you could do:

var separated = "HelloWorld".replace(/(\S)([A-Z])/g, "$1 $2");

In place of "HelloWorld" in the above, you could use any variable containing a string value:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

<script type="text/javascript">
var bob='NannyMcFee';
var separated = bob.replace(/(\S)([A-Z])/g, "$1 $2");

Which also demonstrates that this is not always the optimal way to parse a string with no spaces.