Click here to Skip to main content
15,896,063 members
Articles / Web Development / ASP.NET

Oracle INITCAP equivalent function for SQL, C# and JavaScript

Rate me:
Please Sign up or sign in to vote.
4.33/5 (6 votes)
11 Nov 2011CPOL2 min read 25.1K   5   5
SQL, C# and JavaScript functions for capitalize first letter of the word and keep rest as non-capital.

Introduction

Oracle has an INITCAP function, which returns a string with the first letter of each word in uppercase and keep rest as non-capital. For example: the string 'hello world' would be returned as 'Hello World' and it's a really very nice and useful inbuilt function.

But unfortunately in SQL, C# and even JavaScript no such inbuilt function is available.

Background

In our application, in many places, we required the case when we needed to capitalize first letter of the word and keep the rest as non-capital.

But when I was Googling for a quick answer to this problem, I noticed that there are really no simple solutions listed for it in the web world.

That’s why I decided to build functions in SQL, C# and JavaScript. These functions are very easy to use and also work fine with strings that include numbers.

Using the Code

1. SQL Function

SQL
-- =============================================
-- Author: Samrat
-- Create date:  <Create Date, ,>
-- Description:    SQl function for capitalize first letter of the word and 
-- keep rest as non-capital 
=============================================
CREATE FUNCTION [dbo].[InitCapital] 
(@input_string varchar(1000))
 RETURNS varchar(1000)
AS
BEGIN
    DECLARE @alphabatList varchar(50)
SET @input_string=' '+lower(@input_string)

 DECLARE @cposition SMALLINT, @str VARCHAR(8000)
     SET @alphabatList  = 'a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z'
     
    WHILE @alphabatList <> ''  
    BEGIN  
        SET @cposition = CHARINDEX(',', @alphabatList)  
        IF @cposition>0  
            BEGIN  
                SET @str = LEFT(@alphabatList, @cposition-1) 
                SET @alphabatList = RIGHT(@alphabatList, LEN(@alphabatList)-@cposition)  
                SET @input_string = replace(@input_string,' '+@str,' '+UPPER(@str))
            END  
        ELSE  
            BEGIN  
                SET @str = @alphabatList 
                SET @alphabatList = '' 
                SET @input_string = replace(@input_string,' '+@str,' '+UPPER(@str)) 
            END  
        
    END
    RETURN ltrim(@input_string) 

END

-- Ex. : SELECT dbo.InitCapital('hEllO wOrlD')

2. C# Function

Before move on to the below C# function, I would like to share about .NET inbuilt function which provides the same functionality.
Yes, we can also use the CultureInfo from Globalization and use the TextInfo’s ToTitleCase method in C# for the same purpose.
But one limitation with this method is that, this method does not currently provide proper casing to convert a word that is entirely uppercase, such as an acronym, i.e., if you are using System.Globalization.TextInfo.ToTitleCase(string s)then it works fine if you pass in an all lower or mixed case string. But if you are trying to make amends for data entry staff who like to leave Caps Lock on all the time, so all the input is in upper case.
ToTitleCase("HELLO WORLD") returns "HELLO WORLD" instead of "Hello World".

And we manage this limitation in the below function, in this function you don’t need to care about provided string format. This function internally manages this and provides proper desired result.

C#
public string InitCapitalConvert(string input_string)
   {
       input_string = ' ' + input_string.ToLower();
         
       string[] AlphabatList  = new string[] {"a","b","c","d","e","f","g",
    "h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};

       foreach (string alpha in AlphabatList )
       {
         input_string =  input_string.Replace(' '+alpha,' '+alpha.ToUpper());
       }
       return input_string;
   }

3. JavaScript Function

JavaScript
<script type="text/javascript">

   String.prototype.toINITCAP = function () {
       val = this;
       newVal = '';
       val = val.toLowerCase().split(' ');
       for (var c = 0; c < val.length; c++) {
           newVal += val[c].substring(0, 1).toUpperCase() +
             val[c].substring(1, val[c].length) + ' ';
       }
       return newVal;
   }

   function ShowInitCap() {
       var s = "HeLLo wOrld";
       var t = s.toINITCAP();
       alert(t);
   }

   ShowInitCap();

</script>

For more details, please refer to the uploaded code.

History

  • 12th November, 2011: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
India India
Hi, I am Samrat Banerjee from India.
I am a Software Engineer working in .net platform.
I love to explore new technologies.

Comments and Discussions

 
GeneralMy vote of 5 Pin
vikramasinghchouhan14-Mar-12 22:56
vikramasinghchouhan14-Mar-12 22:56 
GeneralMy vote of 5 Pin
shwetamber29-Dec-11 18:55
shwetamber29-Dec-11 18:55 
QuestionI wont vote but: Pin
HaBiX15-Nov-11 21:37
HaBiX15-Nov-11 21:37 
This functions are highly inefficient.

The c# version returns extra space in front of string, it doesn't accept other chars than you supplied (lets say 'š', 'č', 'ž', ...) You make 30 replaces even if the string is 1 word.

None of the functions supports "whitespace characters" as word delimiters.



Your goal to mimic Oracle's INITCAP function is not successful
Question[My vote of 2] My vote of 2 Pin
tonysawyer15-Nov-11 0:27
tonysawyer15-Nov-11 0:27 
GeneralMy vote of 2 Pin
agorby12-Nov-11 22:02
agorby12-Nov-11 22:02 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.