Uppercase first letter of variable - javascript

I have searched over the web and I can't find anything to help me. I want to make the first letter of each word upper case within a variable.
So far I have tried:
toUpperCase();
And I didn't have any luck, as it uppercases all letters.

Use the .replace function to replace the lowercase letters that begin a word with the capital letter.
var str = "hello, world!";
str = str.toLowerCase().replace(/\b[a-z]/g, function(letter) {
return letter.toUpperCase();
});
alert(str); //Displays "Hello, World!"
If you are dealing with word characters other than just a-z, then the following (more complicated) regular expression might better suit your purposes.
var str = "петр данилович björn über ñaque αλφα";
str = str.toLowerCase().replace(/^[\u00C0-\u1FFF\u2C00-\uD7FF\w]|\s[\u00C0-\u1FFF\u2C00-\uD7FF\w]/g, function(letter) {
return letter.toUpperCase();
});
alert(str); //Displays "Петр Данилович Björn Über Ñaque Αλφα"

A much easier way:
$('#test').css('textTransform', 'capitalize');
I have to give Rafael Herscovici some credit for leading me down the right path. It is far simpler than whatever you guys are proposing.

http://phpjs.org/functions/ucwords:569 has a good example
function ucwords (str) {
return (str + '').replace(/^([a-z])|\s+([a-z])/g, function ($1) {
return $1.toUpperCase();
});
}
(omitted function comment from source for brevity. please see linked source for details)
EDIT: Please note that this function uppercases the first letter of each word (as your question asks) and not just the first letter of a string (as your question title asks)

Here is a pure JavaScript solution (no jQuery):
function capitalize(str) {
strVal = '';
str = str.split(' ');
for (var chr = 0; chr < str.length; chr++) {
strVal += str[chr].substring(0, 1).toUpperCase() + str[chr].substring(1, str[chr].length) + ' '
}
return strVal
}
console.log(capitalize('hello world'));

I imagine you could use substring() and toUpperCase() to pull out the first character, uppercase it, and then replace the first character of your string with the result.
myString = "cheeseburger";
firstChar = myString.substring( 0, 1 ); // == "c"
firstChar.toUpperCase();
tail = myString.substring( 1 ); // == "heeseburger"
myString = firstChar + tail; // myString == "Cheeseburger"
I think that should work for you. Another thing to consider is that if this data is being displayed, you can add a class to its container that has the CSS property "text-transform: capitalize".

To do this, you don't really even need JavaScript if you're going to use
$('#test').css('text-transform', 'capitalize');
Do this as CSS like:
#test,h1,h2,h3 { text-transform: capitalize; }
Or do it as a class and apply that class to wherever you need it:
.ucwords { text-transform: capitalize; }

It is as simple as the following:
string = 'test';
newString = string[0].toUpperCase() + string.slice(1);
alert(newString);

Ever heard of substr()?
For a starter:
$("#test").text($("#test").text().substr(0,1).toUpperCase()+$("#test").text().substr(1,$("#test").text().length));
Thanks to #FelixKling for the tip:
$("#test").text(function(i, text) {
return text.substr(0,1).toUpperCase() + text.substr(1);
});

Building on Peter Olson's answer, I took a more object-oriented approach without jQuery:
String.prototype.ucwords = function() {
return this.toLowerCase().replace(/\b[a-z]/g, function(letter) {
return letter.toUpperCase();
});
}
alert("hello, world!".ucwords()); // Displays "Hello, World!"
Example: http://jsfiddle.net/LzaYH/1/

The simplest way
let str = "hiren raiyani"
str.toLowerCase().replace(/(?<= )[^\s]|^./g, a => a.toUpperCase());
User-defined function:
function capitalize(str){
return str.toLowerCase().replace(/(?<= )[^\s]|^./g, a => a.toUpperCase());
}
Output: Hiren Raiyani
Use code as your user-defined function or direct.

var mystring = "hello World"
mystring = mystring.substring(0,1).toUpperCase() +
mystring.substring(1,mystring.length)
console.log(mystring) //gives you Hello World

var ar = 'foo bar spam egg'.split(/\W/);
for(var i=0; i<ar.length; i++) {
ar[i] = ar[i].substr(0,1).toUpperCase() + ar[i].substr(1,ar[i].length-1)
}
ar.join(' '); // Foo Bar Spam Egg

You can try this simple code with the features of ucwords in PHP.
function ucWords(text) {
return text.split(' ').map((txt) => (txt.substring(0, 1).toUpperCase() + txt.substring(1, txt.length))).join(' ');
}
ucWords('hello WORLD');
It will keep the Upper Cases unchanged.

You can use text-transform: capitalize; for this work.
HTML
<input type="text" style="text-transform: capitalize;" />
jQuery
$(document).ready(function (){
var asdf = "WERTY UIOP";
$('input').val(asdf.toLowerCase());
});
Try This
Note: It's only changing the visual representation of the string. If you alert() this string, it will always show the original value of the string.

Based completely on Rafael Herscovici's answer, this solution is ready to call with a simple jQuery method, 'ucwords'...
$.extend({
ucwords : function(str) {
strVal = '';
str = str.split(' ');
for (var chr = 0; chr < str.length; chr++) {
strVal += str[chr].substring(0, 1).toUpperCase() + str[chr].substring(1, str[chr].length) + ' '
}
return strVal
}
});
Example:
This can be called using the method
var string = "this is a test";
string = $.ucwords(string); // Returns "This Is A Test"

Without JQuery
String.prototype.ucwords = function() {
str = this.trim();
return str.replace(/(^([a-zA-Z\p{M}]))|([ -][a-zA-Z\p{M}])/g, function(s){
return s.toUpperCase();
});
};
console.log('hello world'.ucwords()); // Display Hello World

Short and simple answer:
let str = 'this is a string';
let result = str.replace(/\b\w/g, x => x.toUpperCase());
console.log(result); // This Is A String

The easiest way to uppercase the first letter in JavaScript
var string = "made in india";
string = string.toLowerCase().replace(/\b[a-z]/g, function(letter){return letter.toUpperCase();});
alert(string);
Result:
"Made In India"

Use the below function:
const capitalize = (s) => {
if (typeof s !== 'string')
return ''
return s.charAt(0).toUpperCase() + s.slice(1)
}
capitalize('test') // 'Test'
capitalize('name') // 'Name'

I have used this code -
function ucword(str){
str = str.toLowerCase().replace(/(^([a-zA-Z\p{M}]))|([ -][a-zA-Z\p{M}])/g, function(replace_latter) {
return replace_latter.toUpperCase();
}); //Can use also /\b[a-z]/g
return str; //First letter capital in each word
}
var uc = ucword("good morning. how are you?");
alert(uc);

There sure are a lot of ways to do this!
One thing that I think people forget is that strings are arrays of characters. So, the first letter of any string will be the 'zeroth' element of its array:
let word = 'interesting';
console.log(word[0]);
// 'i'
The simplest way to take advantage of this fact for the purpose of uppercasing the first letter (afaik) would be:
let word = 'interesting';
let titleCase = word[0].toUpperCase() + word.substr(1);
console.log(titleCase);
// 'Interesting'
...or as a function:
function toTitleCase(word) {
return word[0].toUpperCase() + word.substr(1);
}

I think, the method should not convert any other letters than just the very first or the very first of any letter.
My solution for that are the following regexes:
function capitalize( str ){
return str.replace(/^\w/, (s) => s.toUpperCase() );
}
function capitalizeAll( str ){
return str.replace(/(\b\w)/g, (s) => s.toUpperCase() );
}
let test = 'hello world';
capitalize( test ); // Hello world
capitalizeAll( test ); // Hello World

The string to lower before capitalizing the first letter.
(Both use jQuery syntax)
function CapitaliseFirstLetter(elementId) {
var txt = $("#" + elementId).val().toLowerCase();
$("#" + elementId).val(txt.replace(/^(.)|\s(.)/g, function($1) {
return $1.toUpperCase();
}));
}
In addition a function to Capitalise the WHOLE string:
function CapitaliseAllText(elementId) {
var txt = $("#" + elementId).val();
$("#" + elementId).val(txt.toUpperCase());
}
Syntax to use on a textbox's click event:
onClick="CapitaliseFirstLetter('TextId'); return false"

var str = "HELLO WORLD HELLO WORLD HELLO WORLD HELLO WORLD";
str = str.replace(
/([A-Z])([A-Z]+)/g,
function (a, w1, w2) {
return w1 + w2.toLowerCase();
});
alert(str);

Here is Unicode-safe ucwords() function, which additionally respects double-lastnames like Russian Засс-Ранцев and some noble names like Honoré de Balzac, d'Artagnan, Vincent van Gogh, Otto von Bismarck, Sulaymān ibn Dāwūd, etc.:
String.prototype.ucwords = function() {
return this.toLowerCase()
.replace(/(^|\s|\-)[^\s$]/g, function(m) {
return m.toUpperCase();
})
// French, Arabic and some noble names...
.replace(/\s(Of|De|Van|Von|Ibn|Из|Ван|Фон|Ибн)\s/g, function(m) { // Honoré de Balzac, Vincent van Gogh, Otto von Bismarck, Sulaymān ibn Dāwūd etc.
return m.toLowerCase();
})
.replace(/(^|\s)(D|Д)(['’][^\s$])/g, function(m, p1, p2, p3) { // D'Artagnan or d'Artagnan / Д’Артаньян или д’Артаньян
return p1 + (p1 === "" ? p2/*.toUpperCase()*/ : p2.toLowerCase()) + p3.toUpperCase();
});
}

var country = $('#country').val();
var con = country[0].toUpperCase();
ctr = country.replace(country[0], con);
There isn't any need to create any function, just jugaaar.

HTML:
<input class="capitalize" name="Address" type="text" value="" />
JavaScript with jQuery:
$(".capitalize").bind("keyup change", function (e) {
if ($(this).val().length == 1)
$(this).val($(this).val().toUpperCase());
$(this).val($(this).val().toLowerCase().replace(/\s[\p{L}a-z]/g, function (letter) {
return letter.toUpperCase();
}))
});

Related

JavaScript - How to underline the first character of every word

Sentence: Mr Blue has a blue house and a blue car.
JavaScript Code:
`
function myFunction(){
var str = document.getElementById("sentence").innerHTML;
for(var i=0; i<str.length;i++){
if(i == 0 )
{
var res = str.replace(str.charAt(i+1), "<u>"+str.charAt(i+1)+"</u>");
document.getElementById("sentence").innerHTML = res;
}else if(str.charAt(i) == " ")
{
var res = str.replace(str.charAt(i+1), "<u>"+str.charAt(i+1)+"</u>");
document.getElementById("sentence").innerHTML = res;
}
}`
Problem: I am trying to underline the first character in every word of a paragraph when a button is pressed. With the code I have only the C from car is underlined. if anyone can see where I have gone wrong or if there is a better way of doing this problem.
Thanks
Your code is working partially correct. It works on every word of the string but is getting updated again with next word.
You can make it simple by using a regex.
str.replace(/([^\s]+)/g,function(str){
return "<u>"+str.charAt(0)+"</u>" + str.slice(1);
})
Explanation of the regex:
(: Capturing group start
[^: Negated set - Match anything which is not in the set.
\s: Matches any whitespace character (spaces)
]: set ends
): Capturing group ends
Looking at the syntax of the javascript replace function:
str.replace(regexp|substr, newSubstr|function)
function (replacement)
A function to be invoked to create the new substring to be used to
replace the matches to the given regexp or substr. The arguments
supplied to this function are match, submatch, offset and the
original string. (Source: MDN)
Edit: You are still not using the accepted solution in your answer properly. This is how your function will look now:
<script>
function myFunction() {
var str = document.getElementById("Sentence").innerHTML;
var result = str.replace(/([^\s]+)/g,function(str){
return "<u>"+str.charAt(0)+"</u>" + str.slice(1);
});
document.getElementById("Sentence").innerHTML = result;
}
</script>
and if you are comfortable with ES6:
<script>
function myFunction() {
const str = document.getElementById("Sentence").innerHTML;
const result = str.replace(/([^\s]+)/g, p1 => `<u>${p1.charAt(0)}</u>${p1.slice(1)}` );
document.getElementById("Sentence").innerHTML = result;
}
</script>
You store the mutation inside res, but you don't update str, so at the next iteration the previous changes get discarded. Instead just mutate str:
str = str.replace(str.charAt(i+1), "<u>"+str.charAt(i+1)+"</u>");
And then after the loop is done reflect it to the DOM once:
document.getElementById("sentence").innerHTML = str;
How i would solve that:
function underline(selector) {
const el = document.querySelectorAll(selector);
let result = "";
for(const word of el.innerHTML.split(" ")) {
result += `<u>${word[0]}</u>${word.substr(1)}`;
}
el.innerHtML = result;
}
underline("#sentence");
var str = document.getElementById("sentence").innerHTML;
var words = str.match(/\S*/g);
var words2 = [];
words.forEach(function(item, i, arr) {
if (item!="")
{
words2.push(item.replace(item.charAt(1), "<u>"+item.charAt(1)+"</a>"));
}
});
document.getElementById("sentence").innerHTML = words2.join(" ");
Thanks guys for the help, greatly appreciated.
Full Solutions:
<!DOCTYPE html>
<html>
<body>
<p id="Sentence">Mr Blue has a blue house and a blue car.</p>
<button onclick="myFunction()">Click</button>
<script>
function myFunction() {
var str = document.getElementById("Sentence").innerHTML;
var res = str.replace(/([^\s]+)/g,function(str){
return "<u>"+str.charAt(0)+"</u>" + str.slice(1);
});
document.getElementById("Sentence").innerHTML = res;
}
</script>
</body>
</html>

JavaScript titleCase function without regex

I am trying to make a function that takes a string and return a string with all the first latters of a word in uppercase and the rest in lowercase.
Here is what I have:
function titleCase(str) {
str.toLowerCase();
var strAr = str.split(" ");
for (var i = 0; i < strAr.length; i++) {
strAr[i].charAt(0).toUpperCase();
}
str = strAr.join(" ");
return str;
}
titleCase("I'm a little tea pot");
For example, it should change 'My name is nikos' into 'My Name Is Nikos'
Why is the code above not working?
In your for loop you need to assign a value in your loop, like this:
strAr[i] = strAr[i].charAt(0).toUpperCase();
Another (slightly more organized) way to do this: we will make a function to take a word and capitalize it, then we will make a function that takes a string, splits it on a space, capitalizes each word and rejoins and returns the string. Use it on your own string with titleCase('hi there')
function capitalize(str) {
if(str.length == 0) return str;
return str[0].toUpperCase() + str.substr(1);
}
function titleCase(str) {
return str.split(' ').map(capitalize).join(' ');
}
You will need to do an assignment for your string, so the first capital letter then the rest of the string as a lowercase:
strAr[i] = strAr[i].charAt(0).toUpperCase() + strAr[i].substring(1).toLowerCase();
Note the value strAr[i].charAt(0).toUpperCase() will only return the first character as a capital letter, it will not actually change the string in any way.
Here is a simple example
It's not working because you still need to assign the result of strAr[i].charAt(0).toUpperCase():
strAr[i] = strAr[i].charAt(0).toUpperCase() + strAr[i].slice(1);
It's worth pointing out that the .toUpperCase()/.toLowerCase() methods do not mutate/alter the value of the string (which is why you need to assign it). You can simplify your code to the following:
Example Here
function titleCase(str) {
var strAr = str.toLowerCase().split(' ');
for (var i = 0; i < strAr.length; i++) {
strAr[i] = strAr[i].charAt(0).toUpperCase() + strAr[i].slice(1);
}
return strAr.join(' ');
}
console.log(titleCase('This is a simple test.'));
// This Is A Simple Test.
As an alternative to what you wrote, you could also use the following:
Example Here
function titleCase (str) {
return str.toLowerCase().replace(/(^|\s)(\w)/g, function(x) {
return x.toUpperCase();
});
}
console.log(titleCase('This is a simple test.'));
// This Is A Simple Test.
It will convert the entire input string to lower case, and then capitalize all characters succeeding whitespace (based on the match).
Extends the String class:
Replace every word with a toUpperCase'd version of itself.
String.prototype.capitalize = function() {
return this.replace(/(?:^|\s)\S/g, function(a) { return a.toUpperCase(); });
};
console.log("jose maria gonzales".capitalize());
// Jose Maria Gonzales
use below code for ucword
function titleCase(str) {
return (str + '')
.replace(/^([a-z\u00E0-\u00FC])|\s+([a-z\u00E0-\u00FC])/g, function($1) {
return $1.toUpperCase();
});
}
var data = titleCase("I'm a little tea pot");
document.write(data);
function titleCase(str) {
str = str.split(' ');
var title ="";
var result = [];
for(var i = 0; i < str.length; i++){
title = str[i].toLowerCase();
result.push(title[0].toUpperCase()+title.slice(1));
}
return result.join(' ');
}
console.log(titleCase('This is a simple test.'));
// This Is A Simple Test.
really easy to understand and follow through...
A simple ready-to-use JS function for Title case
function toTitleCase(txt = ''){
if (txt && txt.length > 0) {
const txtInLC = txt.toLowerCase();
txt = txtInLC.substring(0,0) + txtInLC[0].toUpperCase() + txtInLC.substring(1);
}
return txt;
};
toTitleCase('HELLO WORLD')
Some use-cases
input
output
'hello world'
'Hello world'
'Hello World'
'Hello world'
'HELLO World'
'Hello world'
'hello WORLD'
'Hello world'
'HELLO WORLD'
'Hello world'

return first element not empty element of array

I have a string that can have words and spaces.
I want to return the first word inside the string.
My method was:
apply .split(' ') to it to remove the white spaces.
do .filter(function(el){ return (el != '') }
get the first element by using [0]
Is there a more optimized way to this? Maybe regex?
My code:
var string = " foo bar ";
function getFirst(str) {
var separatedString = str.split(' ');
separatedString = separatedString.filter(function (el) {
return (el != '')
})
return separatedString[0];
}
Fiddle
Probably closest equivalent of your code will be this line:
var word1 = s.replace(/\s*(\S+).*/, '$1');
Since you're splitting by space so this code will just grab the very first non-space substring from given input.
You could use trim and split on multiple spaces and use string.length in your filter:
function getFirst(str) {
var separatedString = str.split(/\s+/).filter( function (el) {
return el.length;
});
return separatedString[0];
}
getFirst(' foo-bar foo bar bar#foo '); //=> 'foo-bar'
You can do
var firstWord = string.match(/\S+/)[0];

Convert dash-separated string to camelCase?

For example suppose I always have a string that is delimited by "-". Is there a way to transform
it-is-a-great-day-today
to
itIsAGreatDayToday
Using RegEx?
Yes (edited to support non-lowercase input and Unicode):
function camelCase(input) {
return input.toLowerCase().replace(/-(.)/g, function(match, group1) {
return group1.toUpperCase();
});
}
See more about "replace callbacks" on MDN's "Specifying a function as a parameter" documentation.
The first argument to the callback function is the full match, and subsequent arguments are the parenthesized groups in the regex (in this case, the character after the the hyphen).
Another method using reduce:
function camelCase(str) {
return str
.split('-')
.reduce((a, b) => a + b.charAt(0).toUpperCase() + b.slice(1));
}
You can match on the word character after each dash (-) or the start of the string, or you could simplify by matching the word character after each word boundary (\b):
function camelCase(s) {
return (s||'').toLowerCase().replace(/(\b|-)\w/g, function(m) {
return m.toUpperCase().replace(/-/,'');
});
}
camelCase('foo-bar'); // => 'FooBar'
camelCase('FOo-BaR-gAH'); // => 'FooBarGah'
Here's a demo
var test = 'It-is-a-great-day-today';
function camelize(str) {
return str[0].toLowerCase() + str.replace(/-([a-z])/g, function(a, b) {
return b.toUpperCase();
}).slice(1);
}
console.log(camelize(test));
This should also work:
function camelCase(str) {
return str.replace(/^.|-./g, function(letter, index) {
return index == 0 ? letter.toLowerCase() : letter.substr(1).toUpperCase();
});
}
And IMHO it is little bit more efficient since we're not converting whole input string to lowercase first and then convert to uppercase if needed. This function only converts first letter to lowercase and then every character after hyphen - to uppercase.
See http://jsfiddle.net/54ZcM/
function camelCase(string) {
return string.toLowerCase().replace(/(\-[a-zA-Z])/g, function($1) {
return $1.toUpperCase().replace('-','');
})
}
alert(camelCase('fOo-BarBA-fo'));
I know this question is a bit old but,
Here's my version of camelCase function:
var camelCase = (function () {
var DEFAULT_REGEX = /[-_]+(.)?/g;
function toUpper(match, group1) {
return group1 ? group1.toUpperCase() : '';
}
return function (str, delimiters) {
return str.replace(delimiters ? new RegExp('[' + delimiters + ']+(.)?', 'g') : DEFAULT_REGEX, toUpper);
};
})();
It handles all of the following edge cases:
takes care of both underscores and hyphens by default (configurable with second parameter)
string with unicode characters
string that ends with hyphens or underscore
string that has consecutive hyphens or underscores
Here's a link to live tests: http://jsfiddle.net/avKzf/2/
Here are results from tests:
input: "ab-cd-ef", result: "abCdEf"
input: "ab-cd-ef-", result: "abCdEf"
input: "ab-cd-ef--", result: "abCdEf"
input: "ab-cd--ef--", result: "abCdEf"
input: "--ab-cd--ef--", result: "AbCdEf"
input: "--ab-cd-__-ef--", result: "AbCdEf"
Notice that strings that start with delimiters will result in a uppercase letter at the beginning.
If that is not what you would expect, you can always use lcfirst.
Here's my lcfirst if you need it:
function lcfirst(str) {
return str && str.charAt(0).toLowerCase() + str.substring(1);
}
This works great but someone might be able to clean it up.
var toCamelCase = function(str) {
// Replace special characters with a space
str = str.replace(/[^a-zA-Z0-9 ]/g, " ");
// put a space before an uppercase letter
str = str.replace(/([a-z](?=[A-Z]))/g, '$1 ');
// Lower case first character and some other stuff that I don't understand
str = str.replace(/([^a-zA-Z0-9 ])|^[0-9]+/g, '').trim().toLowerCase();
// uppercase characters preceded by a space or number
str = str.replace(/([ 0-9]+)([a-zA-Z])/g, function(a,b,c) {
return b.trim() + c.toUpperCase();
});
return str;
};
console.log(toCamelCase('hyphen~name~ format'));
console.log(toCamelCase('hyphen.name.format'));
console.log(toCamelCase('hyphen-name-format'));
console.log(toCamelCase('Hyphen-Dame-Gormat'));
console.log(toCamelCase('EquipmentClass name'));
console.log(toCamelCase('Equipment className'));
console.log(toCamelCase('equipment class name'));
console.log(toCamelCase(' e Equipment Class Name'));
console.log(toCamelCase('under9score_name_format'));
console.log(toCamelCase('Enderscore_name_format'));
console.log(toCamelCase('EnderscoreBameFormat'));
console.log(toCamelCase('_EnderscoreBameFormat'));
http://jsbin.com/yageqi/1/edit?js,console
'it-is-a-great-day-today'.split('-').map(function(x,i){
return (i?x[0].toUpperCase():x[0]) + x.slice(1).toLowerCase()
}).join('')
Result:
'itIsAGreatDayToday'
Alternatively, .match(/\w+/g) rather than .split('-') -- depending on what you want to do in edge cases like "this--is-a-test".
var string = "it-is-a-great-day-today";
or
var string = "it_is_a_great_day_today";
var regex = /(_|-)([a-z])/g;
string.toLowerCase().replace(regex, toCamelCase );
function toCamelCase( string ){
return string[1].toUpperCase();
}
Output: "itIsAGreatDayToday";
here is the jsfiddle you can play with to test this
http://jsfiddle.net/5n84w/2/
```
/**
* Function to convert any string to camelCase
* var regex = 'chetan-Ankola###.com---m13ok#-#alo(*finding!R%S#%-GFF';
* Where [-_ .] is the seperator, you can add eg: '#' too
* + is to handle repetition of seperator
* ? is to take care of preceeding token
* match nov(ember)? matches nov and november
*/
var camelCaser = function (str) {
var camelCased = str.replace(/[-_ .]+(.)?/g, function (match, p) {
if (p) {
return p.toUpperCase();
}
return '';
}).replace(/[^\w]/gi, '');
return camelCased;
};
```
lodash.camelCase can be another option
Sample:
const str = 'it-is-a-great-day-today';
lodash.camelCase(str.split('-'));
result: itIsAGreatDayToday
Better do this guys,
function camelCase(data) {
var tmp;
if (data && typeof data === 'object') {
forEach(data, function (value, key) {
var tmpvalue = camelCase(key);
tmp[tmpvalue] = value;
});
return tmp;
} else {
return data.toLowerCase().replace(/(\_\w)/g, function (m) { return m[1].toUpperCase() }).replace(/(\-\w)/g, function (m) { return m[1].toUpperCase(); });
}
}
console.log(camelCase("SucCCCess_dfds_dsqsdqs-dsdqs-dqsdqs"));
Works perfectly in any cases.
$scope.toCamelCase = function(arg){
var arg = arg.toLowerCase();
var arr = arg.split("");
arr[0] = arr[0].toUpperCase();
return arr.join("");
};

Remove a letter(:) from a string

I have strings like Name:, Call:, Phone:....and so on in my table. I am learning jQuery and was able to access the text. My tutorial has used trim() to remove any whitespaces. But I want o remove ":" from the end of each string (and yes, it always lies in the end after calling trim() method). So how to achieve it.
Its my code:
<script type="text/javascript">
$(function ()
{
$(':input[type=text], textarea').each
(
function ()
{
var newText = 'Please enter your ' +
$(this).parent().prev().text().toLowerCase().trim();
$(this).attr('value', newText);
}).one('focus', function ()
{
this.value = '', this.className = ''
}).addClass('Watermark').css('width', '300px');
});
</script>
trim(":") did not help...
You can replace all : characters:
var str = '::a:sd:';
str = str.replace(/:/g,''); // str = 'asd';
Or use a handy rtrim() function:
String.prototype.rtrim = function(character) {
var re = new RegExp(character + '*$', 'g');
return this.replace(re, '');
};
var str = '::a:sd:';
str = str.rtrim(':'); // str = '::a:sd';
In this case just use the plain old JavaScript replace or substr methods.
You can also use a regular expression that looks for colon as the last character (the character preceding the regexp end-of-string anchor "$").
"hi:".replace(/:$/, "")
hi
"hi".replace(/:$/, "")
hi
"h:i".replace(/:$/, "")
h:i
This is a simplified, inline version of the rtrim function in Blender's answer.
EDIT: Here is a test fiddle for Blender's corrected rtrim function. Note that his RegExp will delete multiple occurrences of the specified character if the string ends with multiple instances of it consecutively (example bolded below).
http://jsfiddle.net/fGrPb/5/
input = '::a:sd:' output = '::a:sd'; input = 'hi:' output = 'hi'; input = 'hi:::' output = 'hi'; input = 'hi' output = 'hi'; input = 'h:i' output = 'h:i'
To chop the last character of a string use string.slice(0,-1)
You can use a regular expression to remove the colon (:).
Replace one instance:
var with_colon = 'Stuff:';
var regex = /([^:]*):/;
var without_colon = regex.exec(with_colon)[1];
alert(without_colon);
Result: Stuff
Replace all instances:
var with_colon = 'Stuff: Things:';
var without_colon = with_colon.replace(/([^:]*):/g,'$1');
alert(without_colon);
Result: Stuff Things
var myStr = "something:";
myStr = myStr.slice(0, -1);
var a="name:";
var b=a.split(":");
alert(b[0]);
one way is to use lastIndexOf
var str='Name:, Call:, Phone:';
var index=str.lastIndexOf(":");
alert(index);
var s=str.substring(0,index);
alert(s);
DEMO
This checks if the last character is a colon. If it is, the last character is removed.
if (str[str.length - 1] === ":") {
str = str.slice(0, -1);
}
If there can be multiple trailing colons, you can replace if with while, like this:
while (str[str.length - 1] === ":") {
str = str.slice(0, -1);
}
You could even make a generic trim function that accepts a string and a character and trims trailing instances of that character:
var trim = function(str, chr) {
while (str[str.length - 1] === ":") {
str = str.slice(0, -1);
}
return str;
}
function trim(str) {
str = str.replace(/^:*/,"");
return str.replace(/:*$/,"");
}
str = str.substring(0,str.lastIndexOf(":"));
Note that this removes everything from the last : to the end of the string (for example, any whitespace after the :).

Categories

Resources