PDA

View Full Version : Capital letters



marringi
03-22-2008, 02:05 PM
Hello,

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

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

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

marringi
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

jscheuer1
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");
document.write(separated);

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"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

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

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