Related
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'
is there any way to capture and replace all the commas within a string contained within quotation marks and not any commas outside of it. I'd like to change them to pipes, however this:
/("(.*?)?,(.*?)")/gm
is only getting the first instance:
JSBIN
If callbacks are okay, you can go for something like this:
var str = '"test, test2, & test3",1324,,,,http://www.asdf.com';
var result = str.replace(/"[^"]+"/g, function (match) {
return match.replace(/,/g, '|');
});
console.log(result);
//"test| test2| & test3",1324,,,,http://www.asdf.com
This is very convoluted compared to regular expression version, however, I wanted to do this if just for the sake of experiment:
var PEG = require("pegjs");
var parser = PEG.buildParser(
["start = seq",
"delimited = d:[^,\"]* { return d; }",
"quoted = q:[^\"]* { return q; }",
"quote = q:[\"] { return q; }",
"comma = c:[,] { return ''; }",
"dseq = delimited comma dseq / delimited",
"string = quote dseq quote",
"seq = quoted string seq / quoted quote? quoted?"].join("\n")
);
function flatten(array) {
return (array instanceof Array) ?
[].concat.apply([], array.map(flatten)) :
array;
}
flatten(parser.parse('foo "bar,bur,ber" baz "bbbr" "blerh')).join("");
// 'foo "barburber" baz "bbbr" "blerh'
I don't advise you to do this in this particular case, but maybe it will create some interest :)
PS. pegjs can be found here: (I'm not an author and have no affiliation, I simply like PEG) http://pegjs.majda.cz/documentation
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("");
};
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();
}))
});
You can backreference like this in JavaScript:
var str = "123 $test 123";
str = str.replace(/(\$)([a-z]+)/gi, "$2");
This would (quite silly) replace "$test" with "test". But imagine I'd like to pass the resulting string of $2 into a function, which returns another value. I tried doing this, but instead of getting the string "test", I get "$2". Is there a way to achieve this?
// Instead of getting "$2" passed into somefunc, I want "test"
// (i.e. the result of the regex)
str = str.replace(/(\$)([a-z]+)/gi, somefunc("$2"));
Like this:
str.replace(regex, function(match, $1, $2, offset, original) { return someFunc($2); })
Pass a function as the second argument to replace:
str = str.replace(/(\$)([a-z]+)/gi, myReplace);
function myReplace(str, group1, group2) {
return "+" + group2 + "+";
}
This capability has been around since Javascript 1.3, according to mozilla.org.
Using ESNext, quite a dummy links replacer but just to show-case how it works :
let text = 'Visit http://lovecats.com/new-posts/ and https://lovedogs.com/best-dogs NOW !';
text = text.replace(/(https?:\/\/[^ ]+)/g, (match, link) => {
// remove ending slash if there is one
link = link.replace(/\/?$/, '');
return `${link.substr(link.lastIndexOf('/') +1)}`;
});
document.body.innerHTML = text;
Note: Previous answer was missing some code. It's now fixed + example.
I needed something a bit more flexible for a regex replace to decode the unicode in my incoming JSON data:
var text = "some string with an encoded 's' in it";
text.replace(/&#(\d+);/g, function() {
return String.fromCharCode(arguments[1]);
});
// "some string with an encoded 's' in it"
If you would have a variable amount of backreferences then the argument count (and places) are also variable. The MDN Web Docs describe the follwing syntax for sepcifing a function as replacement argument:
function replacer(match[, p1[, p2[, p...]]], offset, string)
For instance, take these regular expressions:
var searches = [
'test([1-3]){1,3}', // 1 backreference
'([Ss]ome) ([A-z]+) chars', // 2 backreferences
'([Mm][a#]ny) ([Mm][0o]r[3e]) ([Ww][0o]rd[5s])' // 3 backreferences
];
for (var i in searches) {
"Some string chars and many m0re w0rds in this test123".replace(
new RegExp(
searches[i]
function(...args) {
var match = args[0];
var backrefs = args.slice(1, args.length - 2);
// will be: ['Some', 'string'], ['many', 'm0re', 'w0rds'], ['123']
var offset = args[args.length - 2];
var string = args[args.length - 1];
}
)
);
}
You can't use 'arguments' variable here because it's of type Arguments and no of type Array so it doesn't have a slice() method.