473,834 Members | 1,801 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Changing case in a sentence to Capitalize Case.

Hello,

I am a javascript newbie and I'm stick at one place.

I have a requirement where I will get a sentence in a variable

example

var v1 ="This is a sentence"

Now I have to change the sentence to Capitalize case where the first
alphabet of every word will be in caps

So for above example the output should be

This Is A Sentence

I have found some scripts that can change case to uppercase or
lowercase but I'm not able to come up with a solution for this.

One more thing, there is no limit on the number of words that I'll get
in the sentence. I may get one word or even ten words.

I'm looking for a solution that will work for all scenarios,

Regards,
Rayne
Sep 22 '08 #1
12 4008
On 2008-09-22 18:19, ja***********@g mail.com wrote:
var v1 ="This is a sentence"

Now I have to change the sentence to Capitalize case where the first
alphabet of every word will be in caps
v1 = v1.replace(/\b(\w)/g, function (s, c) {
return c.toUpperCase() ;
});

BTW, your question looks like a typical homework assignment. If that's
the case: letting other people solve your beginner assignments is not a
not a clever idea, if you want to learn the language or have to pass
exams later. If this wasn't homework, please disregard.
- Conrad
Sep 22 '08 #2
ja***********@g mail.com wrote:
I have a requirement where I will get a sentence in a variable

example

var v1 ="This is a sentence"

Now I have to change the sentence to Capitalize case where the first
alphabet of every word will be in caps
You mean _letter_; *not* alphabet, which is a set of letters.

<http://en.wikipedia.or g/wiki/Alphabet>
So for above example the output should be

This Is A Sentence
v1 = v1.replace(/(^|\s)([a-z])/g,
function(m, p1, p2) {
return p1 + p2.toUpperCase( );
});

You may adapt the character class to fit your needs.
PointedEars
--
var bugRiddenCrashP ronePieceOfJunk = (
navigator.userA gent.indexOf('M SIE 5') != -1
&& navigator.userA gent.indexOf('M ac') != -1
) // Plone, register_functi on.js:16
Sep 22 '08 #3
<ja***********@ gmail.comschree f in bericht
news:b2******** *************** ***********@z6g 2000pre.googleg roups.com...
Hello,

I am a javascript newbie and I'm stick at one place.

I have a requirement where I will get a sentence in a variable

example

var v1 ="This is a sentence"

Now I have to change the sentence to Capitalize case where the first
alphabet of every word will be in caps

So for above example the output should be

This Is A Sentence
a) Regular Expressions, but I don't know how to use them.

b) 1:Split string into words; 2:capitalize first letters; 3:concatenate
words into string.
1: look up what var wordarray = []; wordarray = v1.split(' ') will do
2: for all k: wordarray[k] = wordarray[k].charAt(0).toUp perCase() +
wordarray[k].substr(1);
3: check out the join function: output = wordarray.join( ' ');

Tom
Sep 22 '08 #4
Conrad Lender wrote:
On 2008-09-22 18:19, ja***********@g mail.com wrote:
>var v1 ="This is a sentence"

Now I have to change the sentence to Capitalize case where the first
alphabet of every word will be in caps

v1 = v1.replace(/\b(\w)/g, function (s, c) {
return c.toUpperCase() ;
});
\b matches a word boundary; it does not work with non-ASCII letters.
\w matches ASCII letters, decimal digits and `_'.
BTW, your question looks like a typical homework assignment. If that's
the case: letting other people solve your beginner assignments is not a
not a clever idea, if you want to learn the language or have to pass
exams later. If this wasn't homework, please disregard.
Full ACK.
PointedEars
--
Use any version of Microsoft Frontpage to create your site.
(This won't prevent people from viewing your source, but no one
will want to steal it.)
-- from <http://www.vortex-webdesign.com/help/hidesource.htm>
Sep 22 '08 #5
SAM
ja***********@g mail.com a crit :
>
var v1 ="This is a sentence"

Now I have to change the sentence to Capitalize case where the first
alphabet of every word will be in caps
function capitalize( t ) {
t = t.split(' ');
for(var i=0; i<t.length; i++) {
t[i] = t[i].charAt(0).toUp perCase()+t[i].substring(1);
}
return t.join(' ');
}

alert(capitaliz e(v1));
I'm looking for a solution that will work for all scenarios,
alert(capitaliz e('ask google for charAt, join, '+
'substring and split in javaScript'));


HTML :
======
<a href="javascrip t:document.geEl ementById('here ').innerHTML = v1">
capitalize the variable v1</a>

<p id="here" style="text-transform: capitalize"></p>
Sep 22 '08 #6
On 2008-09-22 20:00, Thomas 'PointedEars' Lahn wrote:
Conrad Lender wrote:
..
>v1 = v1.replace(/\b(\w)/g, function (s, c) {
return c.toUpperCase() ;
});
\b matches a word boundary; it does not work with non-ASCII letters.
\w matches ASCII letters, decimal digits and `_'.
Yes, I was assuming simple English sentences, where \b will usually work
(and it doesn't matter when toUpperCase is applied digits or the
underscore). In this case, my earlier example could even be simplified to:

v1 = v1.replace(/\b\w/g, function (c) {
return c.toUpperCase() ;
});

Your character class approach (in your other post) would work if the
character set is known and rather small. Latin1, for example, could use
[a-z*áâãäåæ çèéêëì* ïðñòóôõ öøßùúûü ]. But if we're assuming an random
international setting, this is going to be a lot harder. Creating a
character class that would work on the complete Unicode set would be
almost impossible, and also error prone. It would be simpler to define
custom "word boundary" characters, and just let JavaScript uppercase
everything following them:

var wBound = '\\s,.;:?!\'"';
var rex = new RegExp('(^|[' + wBound + '])([^' + wBound + '])', 'g');

v1 = v1.replace(rex, function (s, g1, g2) {
return g1 + g2.toUpperCase( );
});

wBound would still have to be adjusted as required to include, for
example, different types of quotes, or the Japanese/Chinese full stop
character 。).
- Conrad
Sep 22 '08 #7
Conrad Lender wrote:
On 2008-09-22 20:00, Thomas 'PointedEars' Lahn wrote:
>Conrad Lender wrote:
>>v1 = v1.replace(/\b(\w)/g, function (s, c) { return c.toUpperCase() ;
});
\b matches a word boundary; it does not work with non-ASCII letters.
\w matches ASCII letters, decimal digits and `_'.

Yes, I was assuming simple English sentences, where \b will usually work
(and it doesn't matter when toUpperCase is applied digits or the
underscore).
It matters because it would be needlessly inefficient.
In this case, my earlier example could even be simplified to:

v1 = v1.replace(/\b\w/g, function (c) {
return c.toUpperCase() ;
});
Correct, \b would match the empty string before the \w then.
Your character class approach (in your other post) would work if the
character set is known and rather small. Latin1, for example, could use
[a-z*áâãäåæ çèéêëì* ïðñòóôõ öøßùúûü ]. But if we're assuming an random
international setting, this is going to be a lot harder.
Harder, granted.
Creating a character class that would work on the complete Unicode set
would be almost impossible, and also error prone.
I do not think it any of the above would apply, though. ISTM you are
unaware of the fact that, while the Unicode Standard (4.0) already defines a
finite character set of which ECMAScript implementations only support the
Basic Multilingual Plane (U+0000 to U+FFFF), the number of characters that
can be subject to case switching is even more limited, and that character
ranges can be used in regular expressions, whereas their boundaries can also
be written as Unicode escape sequences.

All it takes is a bit of research on the defined Unicode character ranges
and the scripts (as in writing) they provide support for. Take some Latin
character ranges for example:

/[a-z\u00c0-\u00f6\u00f8-\u00ff\u0100-\u017f\u0180-\u01bf\u01c4-\u024f]/i

(This can be optimized, of course, but it helps [you] to get the picture.)

See also: <http://www.unicode.org/charts/>
It would be simpler to define custom "word boundary" characters, and just
let JavaScript uppercase everything following them:
Would it? ISTM the punctuation of languages is a lot more complicated than
their letters; take Spanish, for example. But then ISTM capitalizing titles
is not something that is common in other languages than English, and some
even consider it deprecated there already. However, for uniformity one
might be inclined to apply this formatting to non-English (song) titles as
well; I have seen that before.
var wBound = '\\s,.;:?!\'"';
var rex = new RegExp('(^|[' + wBound + '])([^' + wBound + '])', 'g');

v1 = v1.replace(rex, function (s, g1, g2) {
return g1 + g2.toUpperCase( );
});
That does not make much sense, though, since with the exception of white
space, and single and double quote, none of those (punctuation) characters
is likely to occur directly before something that can be considered a word
character. In fact, it is customary to have (white) space between those
characters and the word character to be uppercased, so there would never be
a match then.
wBound would still have to be adjusted as required to include, for
example, different types of quotes, or the Japanese/Chinese full stop
character 。).
I am afraid it would have to be rewritten entirely anyway.
PointedEars
--
Anyone who slaps a 'this page is best viewed with Browser X' label on
a Web page appears to be yearning for the bad old days, before the Web,
when you had very little chance of reading a document written on another
computer, another word processor, or another network. -- Tim Berners-Lee
Sep 22 '08 #8
SAM
Thomas 'PointedEars' Lahn a écrit :
Conrad Lender wrote:
>var wBound = '\\s,.;:?!\'"';
var rex = new RegExp('(^|[' + wBound + '])([^' + wBound + '])', 'g');

v1 = v1.replace(rex, function (s, g1, g2) {
return g1 + g2.toUpperCase( );
});

That does not make much sense, though, since with the exception of white
space, and single and double quote, none of those (punctuation) characters
is likely to occur directly before something that can be considered a word
character.
Hu ? at least : ' and " can be found
(the others too if typo)
In fact, it is customary to have (white) space between those
I see no white space after ' or " in following :
l'éléphant ça "trompe" énormément
characters and the word character to be uppercased, so there would never be
a match then.
We never need to capitalize all words of a sentence in any case. It is a
spelling mistake otherwise of grammar in french.
>wBound would still have to be adjusted as required to include, for
example, different types of quotes, or the Japanese/Chinese full stop
character 。).

I am afraid it would have to be rewritten entirely anyway.
and your solution doesn't work for me

'l\'éléphant ça "trompe" énormément'.r eplace(/(^|\s)([a-z])/g,
function(m, p1, p2) {
return p1 + p2.toUpperCase( );
});

result :
L'éléphant ça "trompe" énormément

While Conrad's code gives :
L'Éléphant Ça "Trompe" Énormément
if the charset is e.g. Latin 1 (and not utf-8)

--
sm
Sep 22 '08 #9
On 2008-09-23 00:20, Thomas 'PointedEars' Lahn wrote:
>Creating a character class that would work on the complete Unicode set
would be almost impossible, and also error prone.
I do not think it any of the above would apply, though. ISTM you are
unaware of the fact that, while the Unicode Standard (4.0) already defines a
finite character set of which ECMAScript implementations only support the
Basic Multilingual Plane (U+0000 to U+FFFF), the number of characters that
can be subject to case switching is even more limited, and that character
ranges can be used in regular expressions, whereas their boundaries canalso
be written as Unicode escape sequences.
You're mistaken, I'm quite familiar with Unicode and character set
support in JavaScript.

The BMP has a theoretical limit of 2^16 characters (although not all of
the code points are currently assigned, granted), which gives us an
upper limit of 65536 characters to consider. Yes, it's a finite set.
Note that I said "almost impossible", meaning not practically feasible,
because...
All it takes is a bit of research on the defined Unicode character ranges
and the scripts (as in writing) they provide support for.
... this is still quite an undertaking, and I wouldn't presume to
understand enough about, say, Mongolian or Burmese to decide which of
the characters could/should be converted to uppercase. There are over a
hundred scripts in the BMP, not including the symbol collections.
Take some Latin character ranges for example:

/[a-z\u00c0-\u00f6\u00f8-\u00ff\u0100-\u017f\u0180-\u01bf\u01c4-\u024f]/i

(This can be optimized, of course, but it helps [you] to get the picture.)
Again, I think I've already got a pretty good picture, but thanks for
the effort. Just to illustrate the pitfalls of your approach - out of
only 591 characters (basic latin to latin extended-b), you have

- included all the uppercase characters like À (U+00C0)
- included the × character (U+00D7) which is a symbol
- used the "i" modifier, which is redundant because you have already
listed the exact code points that you want included

That's for a group of characters that we're largely familiar with. Now,
to find out which of the characters in the more exotic groups are
lowercase letters, that would take more than just "a bit of research".

Perhaps somebody else has already collected all the interesting
character ranges, and we could use that information in our character
class, but why should we, if JavaScript's toUpperCase() already does the
right thing with all types of characters? Hence:
>It would be simpler to define custom "word boundary" characters, and just
let JavaScript uppercase everything following them:
Would it? ISTM the punctuation of languages is a lot more complicated than
their letters; take Spanish, for example. But then ISTM capitalizing titles
is not something that is common in other languages than English, and some
even consider it deprecated there already. However, for uniformity one
might be inclined to apply this formatting to non-English (song) titlesas
well; I have seen that before.
That's beside the point. For one thing, to a lesser extent, capitalising
the first letters in titles is also common in some Germanic languages,
in Italian, etc. More importantly, deciding which languages do or do not
use capitalisation, or have deprecated it, or are only using it for
certain words, is beyond what we can do in a simple script function;
that's up to the person requesting the functionality.
>var wBound = '\\s,.;:?!\'"';
var rex = new RegExp('(^|[' + wBound + '])([^' + wBound + '])', 'g');

v1 = v1.replace(rex, function (s, g1, g2) {
return g1 + g2.toUpperCase( );
});
That does not make much sense, though, since with the exception of white
space, and single and double quote, none of those (punctuation) characters
is likely to occur directly before something that can be considered a word
character. In fact, it is customary to have (white) space between those
characters and the word character to be uppercased, so there would never be
a match then.
"is likely"? "it is customary"? That's wishful thinking, just look at
some of the postings in this group (SCNR). You often see people omitting
the space after full stops or commas, for example:

"this is a sentence!and so is this,see?"

It may not be pretty, but there is no doubt that "and" and "see" are
both separate words, and thus should be capitalised.
I am afraid it would have to be rewritten entirely anyway.
I disagree, but YMMV.
- Conrad
Sep 23 '08 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
262
by: Laurence Nuttall | last post by:
In vb 6 when I typed in if then else endif vb 6 would automatically capitalize the if then else and endif words, ..net does not How can i get .net to capitalize keywords?
1
1390
by: Laurence Nuttall | last post by:
In vb 6 when I typed in if then else endif vb 6 would automatically capitalize the if then else and endif words, ..net does not How can i get .net to capitalize keywords?
10
2446
by: Aaron | last post by:
string a = "i have an apple"; i want the output to be "I Have An Apple"; i was able to capitalize the first word but can't figure out how to capitalize every word in that string Thanks, Aaron
10
8379
by: Wonderinguy | last post by:
I have a table with data stored on upper case. I would like to change it proper mixed case. For example : change data from , THIS IS A TEST to This is a test or This Is A Test. Is there any easy way to do this. Thanks
3
13928
by: Addio | last post by:
Hello, MSA Group, Does anyone know how to convert all UPPER CASE text to Initial Caps? I'm familiar with ucase and lcase, but don't know of any function to handle Initial Caps, i.e. every word between non breaking spaces are Capitalized. Thx, Addio
6
2296
by: reynard | last post by:
I have a page that uses this doctype <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> but when I change to this: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> it breaks my javascript. Particularly I have a code that try to set element.style.left, when I use the second doctype, FF complains "Error in parsing value for property 'left'. Declaration dropped"
4
1992
by: =?Utf-8?B?TWFyc2hhbGw=?= | last post by:
In the sentence, "Our efforts in serving "The Pearson Family" span several years," do you capitalize "The" and "Family"?
1
11251
by: mervyn | last post by:
Hi There, I need to 'title case' all the text on my form. There is no 'title case' option available on .css. The only options are lowercase, uppercase and capitalize. /* Capitalize */ text-transform:capitalize;
6
1818
by: Bart Kastermans | last post by:
I am playing with some trees. In one of the procedures I wrote for this I am trying to change self to a different tree. A tree here has four members (val/type/left/right). I found that self = SS does not work; I have to write self.val = SS.val and the same for the other members (as shown below). Is there a better way to do this? In the below self is part of a parse tree, F is the parse tree of a function f with argument x. If a node...
0
10799
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10515
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10554
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10224
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9338
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development projectplanning, coding, testing, and deploymentwithout human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7761
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupr who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6960
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5799
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
3084
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.