Converting any string into camel case
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.
Converting any string into camel case
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.
HOw to apply regex for converting a string to camel case and remove all special chars from the string-Javascript
Try this:
const cC = str => str.replace( /[^a-z0-9]*([a-z0-9])([a-z0-9]*)/ig, (m, u, l) => u.toUpperCase() + l.toLowerCase() + ' ');
console.log(cC("NOT_AVAI")); // o/p to be"Not Avai" console.log(cC("HEY0-therr")); // o/p to be"Hey0 Therr"
JavaScript space-separated string to camelCase
This should do the trick :
function toCamelCase(sentenceCase) {
var out = "";
sentenceCase.split(" ").forEach(function (el, idx) {
var add = el.toLowerCase();
out += (idx === 0 ? add : add[0].toUpperCase() + add.slice(1));
});
return out;
}
Explanation:
sentenceCase.split(" ")
creates and array out of the sentence eg. ["Sentence", "case", "names"]forEach
loops through each variable in the arrayinside the loop each string is lowercased, then the first letter is uppercased(apart for the first string) and the new string is appended to the
out
variable which is what the function will eventually return as the result.
Given string is not converting into camelCase in python?
This works for your current examples. The re.sub
adds a space between any existing <lower><upper> sequence.
import re
def camelCase(string):
string = re.sub(r'(?:(?<=[a-z])(?=[A-Z]))|[^a-zA-Z]', ' ', string).title().replace(' ', '')
return ''.join([string[0].lower() + string[1:]])
differentTypeOfString = ['bird flight', 'BirdFlight', '-BIRD-FLIGHT-', 'Bird-Flight', 'bird_flight', '--bird.flight', 'Bird-FLIGHT', 'birdFLIGHT']
for i in differentTypeOfString:
print(camelCase(i))
Output:
birdFlight
birdFlight
birdFlight
birdFlight
birdFlight
birdFlight
birdFlight
birdFlight
How to convert string to camelCase without using RegEX
Explanation of this simple algorithm:
Your input must have words that split by a certain character, as you need something to identify which part of the string is a word. Let's assume your string has words separated by '//' instead of spaces as you mentioned in the comments, and each of those words is split by '_'.
First you need to split all words in the string into an array, you can use the split() method in order to do that.
Then when iterating through each word, split it again with
split()
but this time with whatever identifies the different words, in our case it's_
.Iterate through each split words, if it's the first word lowercase it using
toLowerCase()
and add it to the new word variable, if not, lowercase it and capitalize the first letter.
And that's it. Here's the implementation:
const inputWithoutCamelCase = 'hello_world // HOW_ARE_YOU // foo_BAR'
function stringToCamelCase(string) {
const allNames = string.split('//')
let camelCasedString = '';
for (const name of allNames) {
camelCasedString += nameToCamelCaseHelper(name);
}
return camelCasedString;
}
function nameToCamelCaseHelper(word) {
const splittedName = word.split('_');
let camelCasedName = '';
for (let i = 0; i < splittedName.length; i++) {
if (i === 0) {
camelCasedName += splittedName[i].toLowerCase();
} else {
camelCasedName += capitalizeFirstLetter(splittedName[i].toLowerCase())
}
}
return camelCasedName;
}
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
stringToCamelCase(inputWithoutCamelCase) // helloWorld howAreYou fooBar
Python: String to CamelCase
You may have a working implementation with slight errors as mentioned in your comments, but I propose that you:
split by the delimiters
apply a capitalization for all but the first of the tokens
rejoin the tokens
My implementation is:
def to_camel_case(text):
s = text.replace("-", " ").replace("_", " ")
s = s.split()
if len(text) == 0:
return text
return s[0] + ''.join(i.capitalize() for i in s[1:])
IMO it makes a bit more sense.
The output from running tests is:
>>> to_camel_case("the_stealth_warrior")
'theStealthWarrior'
>>> to_camel_case("The-Stealth-Warrior")
'TheStealthWarrior'
>>> to_camel_case("A-B-C")
'ABC'
How to convert camelCase to Camel Case?
"thisStringIsGood"
// insert a space before all caps
.replace(/([A-Z])/g, ' $1')
// uppercase the first character
.replace(/^./, function(str){ return str.toUpperCase(); })
displays
This String Is Good
(function() {
const textbox = document.querySelector('#textbox') const result = document.querySelector('#result') function split() { result.innerText = textbox.value // insert a space before all caps .replace(/([A-Z])/g, ' $1') // uppercase the first character .replace(/^./, (str) => str.toUpperCase()) };
textbox.addEventListener('input', split); split();}());
#result { margin-top: 1em; padding: .5em; background: #eee; white-space: pre;}
<div> Text to split <input id="textbox" value="thisStringIsGood" /></div>
<div id="result"></div>
Convert String To camelCase from TitleCase C#
You just need to lower the first char in the array. See this answer
Char.ToLowerInvariant(name[0]) + name.Substring(1)
As a side note, seeing as you are removing spaces you can replace the underscore with an empty string.
.Replace("_", string.Empty)
Julia implementation for converting string to snake_case/CamelCase
This doesn't use "reserved words" as mentioned in the question, but instead assumes that a series of upper case letters (along with preceding numbers if any, for eg. "30MW") is supposed to be a word of its own; while also ensuring that "Price" in "30MWPrice" is seen as a separate word.
function snake_case(camelstring::S) where S<:AbstractString
wordpat = r"
^[a-z]+ | #match initial lower case part
[A-Z][a-z]+ | #match Words Like This
\d*([A-Z](?=[A-Z]|$))+ | #match ABBREV 30MW
\d+ #match 1234 (numbers without units)
"x
smartlower(word) = any(islowercase, word) ? lowercase(word) : word
words = [smartlower(m.match) for m in eachmatch(wordpat, camelstring)]
join(words, "_")
end
using Test
function runtests()
@test snake_case("askBest30MWPrice") == "ask_best_30MW_price"
@test snake_case("welcomeToAIOverlords") == "welcome_to_AI_overlords"
@test snake_case("queryInterface") == "query_interface"
@test snake_case("tst") == "tst"
@test snake_case("1234") == "1234"
@test snake_case("column12Value") == "column_12_value"
@test snake_case("readTOC") == "read_TOC"
end
(Probably Unimportant) Side Note: You can replace [a-z]
with [[:lower:]]
and [A-Z]
with [[:upper:]]
above to make it work for some more languages, for eg. snake_case("helloΩorld")
will then return "hello_ωorld"
. However (like with anything Unicode), there are nuances - for eg., my language (Tamil) doesn't have letter cases, so its letters fall outside both [:lower:]
and [:upper:]
.
A proper Unicode solution using \p{Lo}
, [:digit:]
, and whatever else, is left as an exercise to the reader.
Related Topics
Replace a Regex Capture Group with Uppercase in JavaScript
How to Access Iframe Parent Page Using Jquery
Easy to Understand Definition of "Asynchronous Event"
Calling JavaScript Function in Iframe
Method Overloading in JavaScript
Overriding a JavaScript Function While Referencing the Original
How to Return a View from an Ajax Call in Laravel 5
Print a Div Using JavaScript in Angularjs Single Page Application
How to Move a Div with Arrow Keys
How to Change HTML Object Element Data Attribute Value in JavaScript
How to Delete Document from Firestore Using Where Clause
Fastest Way to Copy a File in Node.Js
Export JavaScript Data to CSV File Without Server Interaction
JavaScript Parser in JavaScript
How to Loop Through All the Elements Returned from Getelementsbytagname
Handling Multiple Catches in Promise Chain