I am trying to convert a csv string to json in javascript.
I referred to the following link first answer: "What Is The Best Way To Convert From Csv To Json When Commas And Quotations May.
However, when I try that, the header contains a comma so I am not able to render a data Table.
const csvToJson = (str, headerList, quotechar = '"', delimiter = ',') => {
const cutlast = (_, i, a) => i < a.length - 1;
// const regex = /(?:[\t ]?)+("+)?(.*?)\1(?:[\t ]?)+(?:,|$)/gm; // no variable chars
const regex = new RegExp(`(?:[\\t ]?)+(${quotechar}+)?(.*?)\\1(?:[\\t ]?)+(?:${delimiter}|$)`, 'gm');
const lines = str.split('\n');
const headers = headerList || lines.splice(0, 1)[0].match(regex).filter(cutlast);
const list = [];
for (const line of lines) {
const val = {};
for (const [i, m] of [...line.matchAll(regex)].filter(cutlast).entries()) {
// Attempt to convert to Number if possible, also use null if blank
val[headers[i]] = (m[2].length > 0) ? Number(m[2]) || m[2] : null;
}
list.push(val);
}
return list;
}
const testString = `name,age,booktitle
John,,Hello World
Mary,3,""Alas, What Can I do?""
Joseph,5,"Waiting, waiting, waiting"
"Donaldson Jones" , six, "Hello, friend!"`;
console.log(csvToJson(testString));
console.log(csvToJson(testString, ['foo', 'bar', 'baz']));
I have also tried to figure out RegExp written but could not understand it.
Can anybody tell me how to remove a comma from that answer or a better suggestion?
Looks like your problem is the attribute names from your current solution. They sometimes have "," in the end.
If that is the case, the simplest solution is just to remove them using the replace method.
console.log( "something,".replace( ",", "" ) )
console.log( "age".replace( ",", "" ) )
I want to write a function to change the characters in a string at even indices to uppercase. I don't want my program to count the spaces as an even index, even if it falls on an even index.
For example: 'This is a test' => 'ThIs Is A TeSt'
I originally had this solution, but I could not get it to work to ignore the space characters when counting the even indices.
function toWeirdCase(string) {
return string.split("").map((x,i) => i%2=== 0 && x!== " " ? x.toUpperCase() : x).join("")
}
This is my second attempt and I don't know why the string elements aren't actually changing to uppercase. Any help on this would be appreciated. It is just returning the original string.
function toWeirdCase(string) {
let indexCount = 0;
let isSpace = false;
for (let i = 0; i < string.length; i++) {
if (string[i] === " ") {
isSpace = true;
}
if (indexCount % 2 === 0 && !isSpace) {
string[indexCount] = string[indexCount].toUpperCase();
}
indexCount++;
isSpace = false;
}
return string;
}
Answer:
You can use a modified reduce function that utilizes a closure as a character counter. This has the benefit of completing the transformation in one pass:
["", ...str].reduce((n =>
(r, c) => r += /\s/.test(c) ? c : c[`to${n++ & 1 ? "Lower" : "Upper"}Case`]())(0)
);
Example:
const biUpperCase = str => ["", ...str].reduce((n =>
(r, c) =>r += /\s/.test(c) ? c : c[`to${n++ & 1 ? "Lower" : "Upper"}Case`]())(0)
);
let test = biUpperCase("This is a Test");
console.log(test);
Explanation:
n is a character counter that keeps track of all non-space characters. You can think of this as an additional index that only worries about non-space characters.
We use this to determine whether or not a character is an even or odd non-space character by performing bitwise AND ( n & 1 ) or, alternatively, by performing a modulus operation ( n % 2 )
r is the accumulator in the Array.prototype.reduce method. This is what is returned by our reduce method.
Since there was no secondary parameter to Array.prototype.reduce, the first index of the Array is used as the accumulator.
This is why we perform ["", ...str] instead of simply [...str].
Syntactically we could also have written [...str].reduce( fn , "" ) instead of ["", ...str].reduce( fn ), but this would alter our succinct code.
c is the current character that we are looking at within the string array. We use RegExp.prototype.match to determine if it's a space character.
if it is we simply add the space to r ( our accumulated string )
if it is not we add a transformed character to r ( our accumulated string )
To determine which case transformation( upper or lower ) should be applied we check if n ( our character counter ) is even or odd.
if n++ & 1 is truthy the case is lower
if n++ & 1 is falsy the case is upper
Aside:
You'll notice in the snippet and code I provided that I changed your parameter name string to str. The reason for this is because String is a built-in Constructor in JavaScript and it's best to never purposefully "cross the streams" when naming variables.
In the current way that you're attempting to use this variable it makes no difference since it's properly scoped, and truthfully it is up to you if you want to take my advice. Just be aware that it could lead to an annoying, invisible problem.
Hope this Helps! Happy Coding!
You could rewind the index counter for a single word.
function toWeirdCase(string) {
return Array
.from(
string,
(i => x => (/[a-z]/i.test(x) ? i++ : (i = 0)) % 2 ? x : x.toUpperCase())
(0)
)
.join('');
}
console.log(toWeirdCase('This is a test')); // 'ThIs Is A TeSt'
A string in javascript is immutable so you will need to do something like :
let test = 'This is a test';
test = toWeirdCase(test); //Here you assign the result
And here is an example solution which ignores spaces in the count
function toWeirdCase(string) {
let count = 0;
return string.split("").map((x) => {
if(x !== " ")
count++;
if(count%2 === 0) return x.toUpperCase();
else return x;
}).join("")
}
let test = 'This is a test';
test = toWeirdCase(test);
console.log(test); //THiS iS a TeSt
Like the comments mention, strings in Javascript are immutable. That being said, you can break down the input string on whitespace, do the transformations, and join back into a string, something like this -
function toWeirdCase(sentence) {
return sentence
.split(' ')
.map(word => word
.split('')
.map((c, i) => i % 2 ? c : c.toUpperCase())
.join('')).join(' ');
}
You could store the number of spaces in a variable in the functions scope.
function toWeirdCase(string) {
let spaceCount = 0;
// Personal preference: I like the reduce fn for this, but a similar thing could be achieved with map
return string.split('').reduce((value, letter, index) => {
if (letter === ' ') spaceCount++;
return value += ((index - spaceCount) % 2)
? letter
: letter.toUpperCase();
},'')
}
This returns the leter if the index ingoring the space count has a remainder when divided by 2.
You can achieve this like so:
const str = "this is a test";
function toWeirdCase(str) {
return str.split(" ").map(word => (
[...word].map((c, i) => i % 2 ?
c.toLowerCase() :
c.toUpperCase())).join("")).join(" ");
}
console.log(toWeirdCase(str));
Updated: to set odd indexes toLowerCase() to handle edge cases like acronyms (ie: currency acronyms; "CA", "USD")
Hope this helps,
I have this string:
var str = "? this is a ? test ?";
Now I want to get this:
var newstr = "this is a ? test";
As you see I want to remove just those ? surrounding (in the beginning and end) that string (not in the middle of string). How can do that using JavaScript?
Here is what I have tried:
var str = "? this is a ? test ?";
var result = str.trim("?");
document.write(result);
So, as you see it doesn't work. Actually I'm a PHP developer and trim() works well in PHP. Now I want to know if I can use trim() to do that in JS.
It should be noted I can do that using regex, but to be honest I hate regex for this kind of jobs. Anyway is there any better solution?
Edit: As this mentioned in the comment, I need to remove both ? and whitespaces which are around the string.
Search for character mask and return the rest without.
This proposal the use of the bitwise not ~ operator for checking.
~ is a bitwise not operator. It is perfect for use with indexOf(), because indexOf returns if found the index 0 ... n and if not -1:
value ~value boolean
-1 => 0 => false
0 => -1 => true
1 => -2 => true
2 => -3 => true
and so on
function trim(s, mask) {
while (~mask.indexOf(s[0])) {
s = s.slice(1);
}
while (~mask.indexOf(s[s.length - 1])) {
s = s.slice(0, -1);
}
return s;
}
console.log(trim('??? this is a ? test ?', '? '));
console.log(trim('abc this is a ? test abc', 'cba '));
Simply use:
let text = '?? something ? really ??'
text = text.replace(/^([?]*)/g, '')
text = text.replace(/([?]*)$/g, '')
console.log(text)
A possible solution would be to use recursive functions to remove the unwanted leading and trailing characters. This doesn't use regular expressions.
function ltrim(char, str) {
if (str.slice(0, char.length) === char) {
return ltrim(char, str.slice(char.length));
} else {
return str;
}
}
function rtrim(char, str) {
if (str.slice(str.length - char.length) === char) {
return rtrim(char, str.slice(0, 0 - char.length));
} else {
return str;
}
}
Of course this is only one of many possible solutions. The function trim would use both ltrim and rtrim.
The reason that char is the first argument and the string that needs to be cleaned the second, is to make it easier to change this into a functional programming style function, like so (ES 2015):
function ltrim(char) {
(str) => {
<body of function>
}
}
// No need to specify str here
function ltrimSpaces = ltrim(' ');
Here is one way to do it which checks for index-out-of-bounds and makes only a single call to substring:
String.prototype.trimChars = function(chars) {
var l = 0;
var r = this.length-1;
while(chars.indexOf(this[l]) >= 0 && l < r) l++;
while(chars.indexOf(this[r]) >= 0 && r >= l) r--;
return this.substring(l, r+1);
};
Example:
var str = "? this is a ? test ?";
str.trimChars(" ?"); // "this is a ? test"
No regex:
uberTrim = s => s.length >= 2 && (s[0] === s[s.length - 1])?
s.slice(1, -1).trim()
: s;
Step-by-step explanation:
Check if the string is at least 2 characters long and if it is surrounded by a specific character;
If it is, then first slice it to remove the surrounding characters then trim it to remove whitespaces;
If not just return it.
In case you're weirded out by that syntax, it's an Arrow Function and a ternary operator.
The parenthesis are superfluous in the ternary by the way.
Example use:
uberTrim(''); // ''
uberTrim(' Plop! '); //'Plop!'
uberTrim('! ...What is Plop?!'); //'...What is Plop?'
Simple approach using Array.indexOf, Array.lastIndexOf and Array.slice functions:
Update: (note: the author has requested to trim the surrounding chars)
function trimChars(str, char){
var str = str.trim();
var checkCharCount = function(side) {
var inner_str = (side == "left")? str : str.split("").reverse().join(""),
count = 0;
for (var i = 0, len = inner_str.length; i < len; i++) {
if (inner_str[i] !== char) {
break;
}
count++;
}
return (side == "left")? count : (-count - 1);
};
if (typeof char === "string"
&& str.indexOf(char) === 0
&& str.lastIndexOf(char, -1) === 0) {
str = str.slice(checkCharCount("left"), checkCharCount("right")).trim();
}
return str;
}
var str = "???? this is a ? test ??????";
console.log(trimChars(str, "?")); // "this is a ? test"
to keep this question up to date using an ES6 approach:
I liked the bitwise method but when readability is a concern too then here's another approach.
function trimByChar(string, character) {
const first = [...string].findIndex(char => char !== character);
const last = [...string].reverse().findIndex(char => char !== character);
return string.substring(first, string.length - last);
}
Using regex
'? this is a ? test ?'.replace(/^[? ]*(.*?)[? ]*$/g, '$1')
You may hate regex but after finding a solution you will feel cool :)
Javascript's trim method only remove whitespaces, and takes no parameters. For a custom trim, you will have to make your own function. Regex would make a quick solution for it, and you can find an implementation of a custom trim on w3schools in case you don't want the trouble of going through the regex creation process. (you'd just have to adjust it to filter ? instead of whitespace
This in one line of code which returns your desire output:
"? this is a ? test ?".slice(1).slice(0,-1).trim();
How can I convert a string into camel case using javascript regex?
EquipmentClass name or
Equipment className or equipment class name or Equipment Class Name
should all become: equipmentClassName.
Looking at your code, you can achieve it with only two replace calls:
function camelize(str) {
return str.replace(/(?:^\w|[A-Z]|\b\w)/g, function(word, index) {
return index === 0 ? word.toLowerCase() : word.toUpperCase();
}).replace(/\s+/g, '');
}
camelize("EquipmentClass name");
camelize("Equipment className");
camelize("equipment class name");
camelize("Equipment Class Name");
// all output "equipmentClassName"
Edit: Or in with a single replace call, capturing the white spaces also in the RegExp.
function camelize(str) {
return str.replace(/(?:^\w|[A-Z]|\b\w|\s+)/g, function(match, index) {
if (+match === 0) return ""; // or if (/\s+/.test(match)) for white spaces
return index === 0 ? match.toLowerCase() : match.toUpperCase();
});
}
If anyone is using lodash, there is a _.camelCase() function.
_.camelCase('Foo Bar');
// → 'fooBar'
_.camelCase('--foo-bar--');
// → 'fooBar'
_.camelCase('__FOO_BAR__');
// → 'fooBar'
To get camelCase
ES5
var camalize = function camalize(str) {
return str.toLowerCase().replace(/[^a-zA-Z0-9]+(.)/g, function(match, chr)
{
return chr.toUpperCase();
});
}
ES6
var camalize = function camalize(str) {
return str.toLowerCase().replace(/[^a-zA-Z0-9]+(.)/g, (m, chr) => chr.toUpperCase());
}
> To get ***C**amel**S**entence**C**ase* or ***P**ascal**C**ase*
var camelSentence = function camelSentence(str) {
return (" " + str).toLowerCase().replace(/[^a-zA-Z0-9]+(.)/g, function(match, chr)
{
return chr.toUpperCase();
});
}
Note :
For those language with accents. Do include À-ÖØ-öø-ÿ with the regex as following
.replace(/[^a-zA-ZÀ-ÖØ-öø-ÿ0-9]+(.)/g This is only for one language. For another language, you have to search and find
I just ended up doing this:
String.prototype.toCamelCase = function(str) {
return str
.replace(/\s(.)/g, function($1) { return $1.toUpperCase(); })
.replace(/\s/g, '')
.replace(/^(.)/, function($1) { return $1.toLowerCase(); });
}
I was trying to avoid chaining together multiple replace statements. Something where I'd have $1, $2, $3 in my function. But that type of grouping is hard to understand, and your mention about cross browser problems is something I never thought about as well.
You can use this solution :
function toCamelCase(str){
return str.split(' ').map(function(word,index){
// If it is the first word make sure to lowercase all the chars.
if(index == 0){
return word.toLowerCase();
}
// If it is not the first word only upper case the first char and lowercase the rest.
return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
}).join('');
}
In Scott’s specific case I’d go with something like:
String.prototype.toCamelCase = function() {
return this.replace(/^([A-Z])|\s(\w)/g, function(match, p1, p2, offset) {
if (p2) return p2.toUpperCase();
return p1.toLowerCase();
});
};
'EquipmentClass name'.toCamelCase() // -> equipmentClassName
'Equipment className'.toCamelCase() // -> equipmentClassName
'equipment class name'.toCamelCase() // -> equipmentClassName
'Equipment Class Name'.toCamelCase() // -> equipmentClassName
The regex will match the first character if it starts with a capital letter, and any alphabetic character following a space, i.e. 2 or 3 times in the specified strings.
By spicing up the regex to /^([A-Z])|[\s-_](\w)/g it will also camelize hyphen and underscore type names.
'hyphen-name-format'.toCamelCase() // -> hyphenNameFormat
'underscore_name_format'.toCamelCase() // -> underscoreNameFormat
Reliable, high-performance example:
function camelize(text) {
const a = text.toLowerCase()
.replace(/[-_\s.]+(.)?/g, (_, c) => c ? c.toUpperCase() : '');
return a.substring(0, 1).toLowerCase() + a.substring(1);
}
Case-changing characters:
hyphen -
underscore _
period .
space
function toCamelCase(str) {
// Lower cases the string
return str.toLowerCase()
// Replaces any - or _ characters with a space
.replace( /[-_]+/g, ' ')
// Removes any non alphanumeric characters
.replace( /[^\w\s]/g, '')
// Uppercases the first character in each group immediately following a space
// (delimited by spaces)
.replace( / (.)/g, function($1) { return $1.toUpperCase(); })
// Removes spaces
.replace( / /g, '' );
}
I was trying to find a JavaScript function to camelCase a string, and wanted to make sure special characters would be removed (and I had trouble understanding what some of the answers above were doing). This is based on c c young's answer, with added comments and the removal of $peci&l characters.
If regexp isn't required, you might want to look at following code I made a long time ago for Twinkle:
String.prototype.toUpperCaseFirstChar = function() {
return this.substr( 0, 1 ).toUpperCase() + this.substr( 1 );
}
String.prototype.toLowerCaseFirstChar = function() {
return this.substr( 0, 1 ).toLowerCase() + this.substr( 1 );
}
String.prototype.toUpperCaseEachWord = function( delim ) {
delim = delim ? delim : ' ';
return this.split( delim ).map( function(v) { return v.toUpperCaseFirstChar() } ).join( delim );
}
String.prototype.toLowerCaseEachWord = function( delim ) {
delim = delim ? delim : ' ';
return this.split( delim ).map( function(v) { return v.toLowerCaseFirstChar() } ).join( delim );
}
I haven't made any performance tests, and regexp versions might or might not be faster.
My ES6 approach:
const camelCase = str => {
let string = str.toLowerCase().replace(/[^A-Za-z0-9]/g, ' ').split(' ')
.reduce((result, word) => result + capitalize(word.toLowerCase()))
return string.charAt(0).toLowerCase() + string.slice(1)
}
const capitalize = str => str.charAt(0).toUpperCase() + str.toLowerCase().slice(1)
let baz = 'foo bar'
let camel = camelCase(baz)
console.log(camel) // "fooBar"
camelCase('foo bar') // "fooBar"
camelCase('FOO BAR') // "fooBar"
camelCase('x nN foo bar') // "xNnFooBar"
camelCase('!--foo-¿?-bar--121-**%') // "fooBar121"
This function by pass cammelcase such these tests
Foo Bar
--foo-bar--
__FOO_BAR__-
foo123Bar
foo_Bar
function toCamelCase(str)
{
var arr= str.match(/[a-z]+|\d+/gi);
return arr.map((m,i)=>{
let low = m.toLowerCase();
if (i!=0){
low = low.split('').map((s,k)=>k==0?s.toUpperCase():s).join``
}
return low;
}).join``;
}
console.log(toCamelCase('Foo Bar'));
console.log(toCamelCase('--foo-bar--'));
console.log(toCamelCase('__FOO_BAR__-'));
console.log(toCamelCase('foo123Bar'));
console.log(toCamelCase('foo_Bar'));
console.log(toCamelCase('EquipmentClass name'));
console.log(toCamelCase('Equipment className'));
console.log(toCamelCase('equipment class name'));
console.log(toCamelCase('Equipment Class Name'));
Here is a one liner doing the work:
const camelCaseIt = string => string.toLowerCase().trim().split(/[.\-_\s]/g).reduce((string, word) => string + word[0].toUpperCase() + word.slice(1));
It splits the lower-cased string based on the list of characters provided in the RegExp [.\-_\s] (add more inside the []!) and returns a word array . Then, it reduces the array of strings to one concatenated string of words with uppercased first letters. Because the reduce has no initial value, it will start uppercasing first letters starting with the second word.
If you want PascalCase, just add an initial empty string ,'') to the reduce method.
The top answer is terse but it doesn't handle all edge cases. For anyone needing a more robust utility, without any external dependencies:
function camelCase(str) {
return (str.slice(0, 1).toLowerCase() + str.slice(1))
.replace(/([-_ ]){1,}/g, ' ')
.split(/[-_ ]/)
.reduce((cur, acc) => {
return cur + acc[0].toUpperCase() + acc.substring(1);
});
}
function sepCase(str, sep = '-') {
return str
.replace(/[A-Z]/g, (letter, index) => {
const lcLet = letter.toLowerCase();
return index ? sep + lcLet : lcLet;
})
.replace(/([-_ ]){1,}/g, sep)
}
// All will return 'fooBarBaz'
console.log(camelCase('foo_bar_baz'))
console.log(camelCase('foo-bar-baz'))
console.log(camelCase('foo_bar--baz'))
console.log(camelCase('FooBar Baz'))
console.log(camelCase('FooBarBaz'))
console.log(camelCase('fooBarBaz'))
// All will return 'foo-bar-baz'
console.log(sepCase('fooBarBaz'));
console.log(sepCase('FooBarBaz'));
console.log(sepCase('foo-bar-baz'));
console.log(sepCase('foo_bar_baz'));
console.log(sepCase('foo___ bar -baz'));
console.log(sepCase('foo-bar-baz'));
// All will return 'foo__bar__baz'
console.log(sepCase('fooBarBaz', '__'));
console.log(sepCase('foo-bar-baz', '__'));
Demo here: https://codesandbox.io/embed/admiring-field-dnm4r?fontsize=14&hidenavigation=1&theme=dark
lodash can do the trick sure and well:
var _ = require('lodash');
var result = _.camelCase('toto-ce héros')
// result now contains "totoCeHeros"
Although lodash may be a "big" library (~4kB), it contains a lot of functions that you'd normally use a snippet for, or build yourself.
return "hello world".toLowerCase().replace(/(?:(^.)|(\s+.))/g, function(match) {
return match.charAt(match.length-1).toUpperCase();
}); // HelloWorld
Because this question needed yet another answer...
I tried several of the previous solutions, and all of them had one flaw or another. Some didn't remove punctuation; some didn't handle cases with numbers; some didn't handle multiple punctuations in a row.
None of them handled a string like a1 2b. There's no explicitly defined convention for this case, but some other stackoverflow questions suggested separating the numbers with an underscore.
I doubt this is the most performant answer (three regex passes through the string, rather than one or two), but it passes all the tests I can think of. To be honest, though, I really can't imagine a case where you're doing so many camel-case conversions that performance would matter.
(I added this as an npm package. It also includes an optional boolean parameter to return Pascal Case instead of Camel Case.)
const underscoreRegex = /(?:[^\w\s]|_)+/g,
sandwichNumberRegex = /(\d)\s+(?=\d)/g,
camelCaseRegex = /(?:^\s*\w|\b\w|\W+)/g;
String.prototype.toCamelCase = function() {
if (/^\s*_[\s_]*$/g.test(this)) {
return '_';
}
return this.replace(underscoreRegex, ' ')
.replace(sandwichNumberRegex, '$1_')
.replace(camelCaseRegex, function(match, index) {
if (/^\W+$/.test(match)) {
return '';
}
return index == 0 ? match.trimLeft().toLowerCase() : match.toUpperCase();
});
}
Test cases (Jest)
test('Basic strings', () => {
expect(''.toCamelCase()).toBe('');
expect('A B C'.toCamelCase()).toBe('aBC');
expect('aB c'.toCamelCase()).toBe('aBC');
expect('abc def'.toCamelCase()).toBe('abcDef');
expect('abc__ _ _def'.toCamelCase()).toBe('abcDef');
expect('abc__ _ d_ e _ _fg'.toCamelCase()).toBe('abcDEFg');
});
test('Basic strings with punctuation', () => {
expect(`a'b--d -- f.h`.toCamelCase()).toBe('aBDFH');
expect(`...a...def`.toCamelCase()).toBe('aDef');
});
test('Strings with numbers', () => {
expect('12 3 4 5'.toCamelCase()).toBe('12_3_4_5');
expect('12 3 abc'.toCamelCase()).toBe('12_3Abc');
expect('ab2c'.toCamelCase()).toBe('ab2c');
expect('1abc'.toCamelCase()).toBe('1abc');
expect('1Abc'.toCamelCase()).toBe('1Abc');
expect('abc 2def'.toCamelCase()).toBe('abc2def');
expect('abc-2def'.toCamelCase()).toBe('abc2def');
expect('abc_2def'.toCamelCase()).toBe('abc2def');
expect('abc1_2def'.toCamelCase()).toBe('abc1_2def');
expect('abc1 2def'.toCamelCase()).toBe('abc1_2def');
expect('abc1 2 3def'.toCamelCase()).toBe('abc1_2_3def');
});
test('Oddball cases', () => {
expect('_'.toCamelCase()).toBe('_');
expect('__'.toCamelCase()).toBe('_');
expect('_ _'.toCamelCase()).toBe('_');
expect('\t_ _\n'.toCamelCase()).toBe('_');
expect('_a_'.toCamelCase()).toBe('a');
expect('\''.toCamelCase()).toBe('');
expect(`\tab\tcd`.toCamelCase()).toBe('abCd');
expect(`
ab\tcd\r
-_
|'ef`.toCamelCase()).toBe(`abCdEf`);
});
To effectively create a function that converts the casing of a string to camel-case, the function will also need to convert each string to lower-case first, before transforming the casing of the first character of non-first strings to an uppercase letter.
My example string is:
"text That I WaNt to make cAMEL case"
Many other solutions provided to this question return this:
"textThatIWaNtToMakeCAMELCase"
What I believe should be the expected, desired output would be this though, where all the mid-string uppercase characters are first transformed to be lowercase:
"textThatIWanrtToMakeCamelCase"
This can be done WITHOUT using any replace() method calls, by utilizing the String.prototype.split(), Array.prototype.map(), and Array.prototype.join() methods:
≤ ES5 Version
function makeCamelCase(str) {
return str
.split(' ')
.map((e,i) => i
? e.charAt(0).toUpperCase() + e.slice(1).toLowerCase()
: e.toLowerCase()
)
.join('')
}
makeCamelCase("text That I WaNt to make cAMEL case")
// -> "textThatIWanrtToMakeCamelCase" ✅
I'll break down what each line does, and then provide the same solution in two other formats— ES6 and as a String.prototype method, though I'd advise against extending built-in JavaScript prototypes directly like this.
Explainer
function makeCamelCase(str) {
return str
// split string into array of different words by splitting at spaces
.split(' ')
// map array of words into two different cases, one for the first word (`i == false`) and one for all other words in the array (where `i == true`). `i` is a parameter that denotes the current index of the array item being evaluated. Because indexes start at `0` and `0` is a "falsy" value, we can use the false/else case of this ternary expression to match the first string where `i === 0`.
.map((e,i) => i
// for all non-first words, use a capitalized form of the first character + the lowercase version of the rest of the word (excluding the first character using the slice() method)
? e.charAt(0).toUpperCase() + e.slice(1).toLowerCase()
// for the first word, we convert the entire word to lowercase
: e.toLowerCase()
)
// finally, we join the different strings back together into a single string without spaces, our camel-cased string
.join('')
}
makeCamelCase("text That I WaNt to make cAMEL case")
// -> "textThatIWanrtToMakeCamelCase" ✅
Condensed ES6+ (One-Liner) Version
const makeCamelCase = str => str.split(' ').map((e,i) => i ? e.charAt(0).toUpperCase() + e.slice(1).toLowerCase() : e.toLowerCase()).join('')
makeCamelCase("text That I WaNt to make cAMEL case")
// -> "textThatIWanrtToMakeCamelCase" ✅
String.prototype method version
String.prototype.toCamelCase = function() {
return this
.split(' ')
.map((e,i) => i
? e.charAt(0).toUpperCase() + e.slice(1).toLowerCase()
: e.toLowerCase()
)
.join('')
}
"text That I WaNt to make cAMEL case".toCamelCase()
// -> "textThatIWanrtToMakeCamelCase" ✅
little modified Scott's answer:
toCamelCase = (string) ->
string
.replace /[\s|_|-](.)/g, ($1) -> $1.toUpperCase()
.replace /[\s|_|-]/g, ''
.replace /^(.)/, ($1) -> $1.toLowerCase()
now it replaces '-' and '_' too.
All 14 permutations below produce the same result of "equipmentClassName".
String.prototype.toCamelCase = function() {
return this.replace(/[^a-z ]/ig, '') // Replace everything but letters and spaces.
.replace(/(?:^\w|[A-Z]|\b\w|\s+)/g, // Find non-words, uppercase letters, leading-word letters, and multiple spaces.
function(match, index) {
return +match === 0 ? "" : match[index === 0 ? 'toLowerCase' : 'toUpperCase']();
});
}
String.toCamelCase = function(str) {
return str.toCamelCase();
}
var testCases = [
"equipment class name",
"equipment class Name",
"equipment Class name",
"equipment Class Name",
"Equipment class name",
"Equipment class Name",
"Equipment Class name",
"Equipment Class Name",
"equipment className",
"equipment ClassName",
"Equipment ClassName",
"equipmentClass name",
"equipmentClass Name",
"EquipmentClass Name"
];
for (var i = 0; i < testCases.length; i++) {
console.log(testCases[i].toCamelCase());
};
you can use this solution:
String.prototype.toCamelCase = function(){
return this.replace(/\s(\w)/ig, function(all, letter){return letter.toUpperCase();})
.replace(/(^\w)/, function($1){return $1.toLowerCase()});
};
console.log('Equipment className'.toCamelCase());
Here's my suggestion:
function toCamelCase(string) {
return `${string}`
.replace(new RegExp(/[-_]+/, 'g'), ' ')
.replace(new RegExp(/[^\w\s]/, 'g'), '')
.replace(
new RegExp(/\s+(.)(\w+)/, 'g'),
($1, $2, $3) => `${$2.toUpperCase() + $3.toLowerCase()}`
)
.replace(new RegExp(/\s/, 'g'), '')
.replace(new RegExp(/\w/), s => s.toLowerCase());
}
or
String.prototype.toCamelCase = function() {
return this
.replace(new RegExp(/[-_]+/, 'g'), ' ')
.replace(new RegExp(/[^\w\s]/, 'g'), '')
.replace(
new RegExp(/\s+(.)(\w+)/, 'g'),
($1, $2, $3) => `${$2.toUpperCase() + $3.toLowerCase()}`
)
.replace(new RegExp(/\s/, 'g'), '')
.replace(new RegExp(/\w/), s => s.toLowerCase());
};
Test cases:
describe('String to camel case', function() {
it('should return a camel cased string', function() {
chai.assert.equal(toCamelCase('foo bar'), 'fooBar');
chai.assert.equal(toCamelCase('Foo Bar'), 'fooBar');
chai.assert.equal(toCamelCase('fooBar'), 'fooBar');
chai.assert.equal(toCamelCase('FooBar'), 'fooBar');
chai.assert.equal(toCamelCase('--foo-bar--'), 'fooBar');
chai.assert.equal(toCamelCase('__FOO_BAR__'), 'fooBar');
chai.assert.equal(toCamelCase('!--foo-¿?-bar--121-**%'), 'fooBar121');
});
});
following #Scott's readable approach, a little bit of fine tuning
// convert any string to camelCase
var toCamelCase = function(str) {
return str.toLowerCase()
.replace( /['"]/g, '' )
.replace( /\W+/g, ' ' )
.replace( / (.)/g, function($1) { return $1.toUpperCase(); })
.replace( / /g, '' );
}
There is my solution:
const toCamelWord = (word, idx) =>
idx === 0 ?
word.toLowerCase() :
word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
const toCamelCase = text =>
text
.split(/[_-\s]+/)
.map(toCamelWord)
.join("");
console.log(toCamelCase('User ID'))
This method seems to outperform most answers on here, it's a little bit hacky though, no replaces, no regex, simply building up a new string that's camelCase.
String.prototype.camelCase = function(){
var newString = '';
var lastEditedIndex;
for (var i = 0; i < this.length; i++){
if(this[i] == ' ' || this[i] == '-' || this[i] == '_'){
newString += this[i+1].toUpperCase();
lastEditedIndex = i+1;
}
else if(lastEditedIndex !== i) newString += this[i].toLowerCase();
}
return newString;
}
This builds on the answer by CMS by removing any non-alphabetic characters including underscores, which \w does not remove.
function toLowerCamelCase(str) {
return str.replace(/[^A-Za-z0-9]/g, ' ').replace(/^\w|[A-Z]|\b\w|\s+/g, function (match, index) {
if (+match === 0 || match === '-' || match === '.' ) {
return ""; // or if (/\s+/.test(match)) for white spaces
}
return index === 0 ? match.toLowerCase() : match.toUpperCase();
});
}
toLowerCamelCase("EquipmentClass name");
toLowerCamelCase("Equipment className");
toLowerCamelCase("equipment class name");
toLowerCamelCase("Equipment Class Name");
toLowerCamelCase("Equipment-Class-Name");
toLowerCamelCase("Equipment_Class_Name");
toLowerCamelCase("Equipment.Class.Name");
toLowerCamelCase("Equipment/Class/Name");
// All output e
Upper camel case ("TestString") to lower camel case ("testString") without using regex (let's face it, regex is evil):
'TestString'.split('').reduce((t, v, k) => t + (k === 0 ? v.toLowerCase() : v), '');
I ended up crafting a slightly more aggressive solution:
function toCamelCase(str) {
const [first, ...acc] = str.replace(/[^\w\d]/g, ' ').split(/\s+/);
return first.toLowerCase() + acc.map(x => x.charAt(0).toUpperCase()
+ x.slice(1).toLowerCase()).join('');
}
This one, above, will remove all non-alphanumeric characters and lowercase parts of words that would otherwise remain uppercased, e.g.
Size (comparative) => sizeComparative
GDP (official exchange rate) => gdpOfficialExchangeRate
hello => hello
function convertStringToCamelCase(str){
return str.split(' ').map(function(item, index){
return index !== 0
? item.charAt(0).toUpperCase() + item.substr(1)
: item.charAt(0).toLowerCase() + item.substr(1);
}).join('');
}
I know this is an old answer, but this handles both whitespace and _ (lodash)
function toCamelCase(s){
return s
.replace(/_/g, " ")
.replace(/\s(.)/g, function($1) { return $1.toUpperCase(); })
.replace(/\s/g, '')
.replace(/^(.)/, function($1) { return $1.toLowerCase(); });
}
console.log(toCamelCase("Hello world");
console.log(toCamelCase("Hello_world");
// Both print "helloWorld"
const toCamelCase = str =>
str
.replace(/[^a-zA-Z0-9]+(.)/g, (m, chr) => chr.toUpperCase())
.replace(/^\w/, c => c.toLowerCase());