Convert string to snake case in JavaScript
Question:
How to convert string to snake case in JavaScript? Answer:
function toCamelCase(str){
return (' ' + str).toLowerCase().replace(/[^a-zA-Z0-9]+(.)/g, (m, chr) => {
return '_' + chr}).substring(1);
}
console.log(toCamelCase('the name field id is name-field_id'));
Description:
Snake case (stylized as snake_case) refers to the style of writing in which each space is replaced by an underscore (_
) character, and the first letter of each word written in lowercase. It is a commonly used naming convention in computing, for example for variable and subroutine names, and for filenames.
To convert a string to a snake case in JavaScript you can use the replace
method on the string and use regular expressions and callback functions to generate the right output.
Reference:
String replace reference
Share "How to convert string to snake case in JavaScript?"
Related snippets:
- Convert string to int in JavaScript
- Convert string to lowercase with JavaScript
- Capitalize words in a string using JavaScript
- Generate random string in JavaScript
- Generate UUID in JavaScript
- Generate random color with JavaScript
- Convert string to kebab case in JavaScript
- Convert snake case to camel case in JavaScript
- Convert string to character array in JavaScript
- Convert camel case to snake case in JavaScript
- Remove accents from a string in JavaScript
- Convert a string to sentence case in JavaScript
- Convert string to title case in JavaScript
- Convert string to snake case in JavaScript
- Convert string to pascal case in JavaScript
- Convert string to camel case in JavaScript
- Convert string to uppercase with JavaScript
- Convert object to JSON string in JavaScript
- Parse JSON string in JavaScript
- convert number to string in JavaScript
- Use colors in JavaScript console
- Get string length in JavaScript
- Split a string into words
- Replace line break with br in JavaScript
- Replace spaces with dashes in JavaScript
- Create multiline string in JavaScript
Tags:
snake case, snake_case, string, convert, regexp, javascript Technical term:
Convert string to snake case in JavaScript