How can I convert PascalCase string into underscore_case/snake_case string? I need to convert dots into underscores as well.
eg. convert
TypeOfData.AlphaBeta
into
type_of_data_alpha_beta
You could try the below steps.
Capture all the uppercase letters and also match the preceding optional dot character.
Then convert the captured uppercase letters to lowercase and then return back to replace function with an _ as preceding character. This will be achieved by using anonymous function in the replacement part.
This would replace the starting uppercase letter to _ + lowercase_letter.
Finally removing the starting underscore will give you the desired output.
var s = 'TypeOfData.AlphaBeta';
console.log(s.replace(/(?:^|\.?)([A-Z])/g, function (x,y){return "_" + y.toLowerCase()}).replace(/^_/, ""));
OR
var s = 'TypeOfData.AlphaBeta';
alert(s.replace(/\.?([A-Z])/g, function (x,y){return "_" + y.toLowerCase()}).replace(/^_/, ""));
any way to stop it for when a whole word is in uppercase. eg. MotorRPM into motor_rpm instead of motor_r_p_m? or BatteryAAA into battery_aaa instead of battery_a_a_a?
var s = 'MotorRMP';
alert(s.replace(/\.?([A-Z]+)/g, function (x,y){return "_" + y.toLowerCase()}).replace(/^_/, ""));
str.split(/\.?(?=[A-Z])/).join('_').toLowerCase();
u're welcome
var s1 = 'someTextHere';
var s2 = 'SomeTextHere';
var s3 = 'TypeOfData.AlphaBeta';
var o1 = s1.split(/\.?(?=[A-Z])/).join('_').toLowerCase();
var o2 = s2.split(/\.?(?=[A-Z])/).join('_').toLowerCase();
var o3 = s3.split(/\.?(?=[A-Z])/).join('_').toLowerCase();
console.log(o1);
console.log(o2);
console.log(o3);
Alternatively using lodash:
lodash.snakeCase(str);
Example:
_.snakeCase('TypeOfData.AlphaBeta');
// ➜ 'type_of_data_alpha_beta'
Lodash is a fine library to give shortcut to many everyday js tasks.There are many other similar string manipulation functions such as camelCase, kebabCase etc.
This solution solves the non-trailing acronym issue with the solutions above
I ported the code in 1175208 from Python to JavaScript.
Javascript Code
function camelToSnakeCase(text) {
return text.replace(/(.)([A-Z][a-z]+)/, '$1_$2').replace(/([a-z0-9])([A-Z])/, '$1_$2').toLowerCase()
}
Working Examples:
camelToSnakeCase('thisISDifficult') -> this_is_difficult
camelToSnakeCase('thisISNT') -> this_isnt
camelToSnakeCase('somethingEasyLikeThis') -> something_easy_like_this
"alphaBetaGama".replace(/([A-Z])/g, "_$1").toLowerCase() // alpha_beta_gamma
Problem - Need to convert a camel-case string ( such as a property name ) into underscore style to meet interface requirements or for meta-programming.
Explanation
This line uses a feature of regular expressions where it can return a matched result ( first pair of () is $1, second is $2, etc ).
Each match in the string is converted to have an underscore ahead of it with _$1 string provided. At that point the string looks like alpha_Beta_Gamma.
To correct the capitalization, the entire string is converted toLowerCase().
Since toLowerCase is a fairly expensive operation, its best not to put it in the looping handler for each match-case, and run it once on the entire string.
After toLowerCase it the resulting string is alpha_beta_gamma ( in this example )
This will get you pretty far: https://github.com/domchristie/humps
You will probably have to use regex replace to replace the "." with an underscore.
I found this but I edited it so suit your question.
const camelToSnakeCase = str => str.replace(/[A-Z]/g, letter => `_${letter.toLowerCase()}`).replace(/^_/,'')
Good examples for js:
Snake Case
Kebab Case
Camel Case
Pascal Case
have here
function toCamelCase(s) {
// remove all characters that should not be in a variable name
// as well underscores an numbers from the beginning of the string
s = s.replace(/([^a-zA-Z0-9_\- ])|^[_0-9]+/g, "").trim().toLowerCase();
// uppercase letters preceeded by a hyphen or a space
s = s.replace(/([ -]+)([a-zA-Z0-9])/g, function(a,b,c) {
return c.toUpperCase();
});
// uppercase letters following numbers
s = s.replace(/([0-9]+)([a-zA-Z])/g, function(a,b,c) {
return b + c.toUpperCase();
});
return s;
}
Try this function, hope it helps.
"TestString".replace(/[A-Z]/g, val => "_" + val.toLowerCase()).replace(/^_/,"")
replaces all uppercase with an underscore and lowercase, then removes the leading underscore.
A Non-Regex Answer that converts PascalCase to snake_case
Note: I understand there are tons of good answers which solve this question elegantly. I was recently working on something similar to this where I chose not to use regex. So I felt to answer a non-regex solution to this.
const toSnakeCase = (str) => {
return str.slice(0,1).toLowerCase() + str.split('').slice(1).map((char) => {
if (char == char.toUpperCase()) return '_' + char.toLowerCase();
else return char;
}).join('');
}
Eg.
inputString = "ILoveJavascript" passed onto toSnakeCase()
would become "i_love_javascript"
Related
This question already has answers here:
How do you use a variable in a regular expression?
(27 answers)
Closed 2 years ago.
So for example:
function(input){
var testVar = input;
string = ...
string.replace(/ReGeX + testVar + ReGeX/, "replacement")
}
But this is of course not working :)
Is there any way to do this?
const regex = new RegExp(`ReGeX${testVar}ReGeX`);
...
string.replace(regex, "replacement");
Update
Per some of the comments, it's important to note that you may want to escape the variable if there is potential for malicious content (e.g. the variable comes from user input)
ES6 Update
In 2019, this would usually be written using a template string, and the above code has been updated. The original answer was:
var regex = new RegExp("ReGeX" + testVar + "ReGeX");
...
string.replace(regex, "replacement");
You can use the RegExp object:
var regexstring = "whatever";
var regexp = new RegExp(regexstring, "gi");
var str = "whateverTest";
var str2 = str.replace(regexp, "other");
document.write(str2);
Then you can construct regexstring in any way you want.
You can read more about it here.
To build a regular expression from a variable in JavaScript, you'll need to use the RegExp constructor with a string parameter.
function reg(input) {
var flags;
//could be any combination of 'g', 'i', and 'm'
flags = 'g';
return new RegExp('ReGeX' + input + 'ReGeX', flags);
}
of course, this is a very naive example. It assumes that input is has been properly escaped for a regular expression. If you're dealing with user-input, or simply want to make it more convenient to match special characters, you'll need to escape special characters:
function regexEscape(str) {
return str.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')
}
function reg(input) {
var flags;
//could be any combination of 'g', 'i', and 'm'
flags = 'g';
input = regexEscape(input);
return new RegExp('ReGeX' + input + 'ReGeX', flags);
}
You can create regular expressions in JS in one of two ways:
Using regular expression literal - /ab{2}/g
Using the regular expression constructor - new RegExp("ab{2}", "g") .
Regular expression literals are constant, and can not be used with variables. This could be achieved using the constructor. The stracture of the RegEx constructor is
new RegExp(regularExpressionString, modifiersString)
You can embed variables as part of the regularExpressionString. For example,
var pattern="cd"
var repeats=3
new RegExp(`${pattern}{${repeats}}`, "g")
This will match any appearance of the pattern cdcdcd.
if you're using es6 template literals are an option...
string.replace(new RegExp(`ReGeX${testVar}ReGeX`), "replacement")
You can always give regular expression as string, i.e. "ReGeX" + testVar + "ReGeX". You'll possibly have to escape some characters inside your string (e.g., double quote), but for most cases it's equivalent.
You can also use RegExp constructor to pass flags in (see the docs).
It's only necessary to prepare the string variable first and then convert it to the RegEx.
for example:
You want to add minLength and MaxLength with the variable to RegEx:
function getRegEx() {
const minLength = "5"; // for exapmle: min is 5
const maxLength = "12"; // for exapmle: man is 12
var regEx = "^.{" + minLength + ","+ maxLength +"}$"; // first we make a String variable of our RegEx
regEx = new RegExp(regEx, "g"); // now we convert it to RegEx
return regEx; // In the end, we return the RegEx
}
now if you change value of MaxLength or MinLength, It will change in all RegExs.
Hope to be useful. Also sorry about my English.
Here's an pretty useless function that return values wrapped by specific characters. :)
jsfiddle: https://jsfiddle.net/squadjot/43agwo6x/
function getValsWrappedIn(str,c1,c2){
var rg = new RegExp("(?<=\\"+c1+")(.*?)(?=\\"+c2+")","g");
return str.match(rg);
}
var exampleStr = "Something (5) or some time (19) or maybe a (thingy)";
var results = getValsWrappedIn(exampleStr,"(",")")
// Will return array ["5","19","thingy"]
console.log(results)
accepted answer doesn't work for me and doesn't follow MDN examples
see the 'Description' section in above link
I'd go with the following it's working for me:
let stringThatIsGoingToChange = 'findMe';
let flagsYouWant = 'gi' //simple string with flags
let dynamicRegExp = new RegExp(`${stringThatIsGoingToChange}`, flagsYouWant)
// that makes dynamicRegExp = /findMe/gi
I face a problem with regex and string replace and I would love a little bit of help.
I have a string with the following format
<div class="$(unique-result) single-result data-index=$(i)"><div class="airport-data data-index=$(i)">$(name)<br>$(city) ,$(country)</div><div class="airport-code data-index=$(i)">$(IATA)</div></div>
and I need to replace all the $(unique-result) with a string of mine.
I tried the following code but I can't seem to find out why this doesn't work
string.replace(new RegExp('\\$(unique-result)', 'g'), changeString)
The result is the exact same string I gave as an input.
Could anyone help me out but also point out why it didn't work?
Thank you in advance.
You missed escaping. you need to escape properly
let str = `<div class="$(unique-result) single-result data-index=$(i)"><div class="airport-data data-index=$(i)">$(name)<br>$(city) ,$(country)</div><div class="airport-code data-index=$(i)">$(IATA)</div></div>`
let op = str.replace(new RegExp('\\$\\(unique-result\\)','g'), 'Changed')
console.log(op)
In case i am not using any variable i prefer using regex literal (//)
let str = `<div class="$(unique-result) single-result data-index=$(i)"><div class="airport-data data-index=$(i)">$(name)<br>$(city) ,$(country)</div><div class="airport-code data-index=$(i)">$(IATA)</div></div>`
let op = str.replace(/\$\(unique-result\)/g, 'Changed')
console.log(op)
There is more general solution.
First of all, as I mentioned in comments, you don't need to use the RegExp constructor, you can simply pass your regexp between slashes and use flags after last slash:
str.replace(/\$\(unique-result\)/g, "someValue")
The second moment is that String.prototype.replace can accept a function as a second parameter. This will be helpful when there is a lot of named templates in you string. For example, you have the next incoming string:
var incomingString = "$(first-value) says $(second-value) when there is $(third-value)"
With code that you've provided you should call replace 3 times. But if you will use a function as a second parameter, this can be simplified to:
var incomingString = "$(first-value) says $(second-value) when there is $(third-value)"
var data = {
"first-value": "Kappa",
"second-value": "Hey!",
"third-value": "GreyFaceNoSpace"
}
var resultString = incomingString.replace(/\$\(([^)]+)\)/g, (match, capture) => {
console.log(match, capture)
return data[capture]
})
console.log(resultString)
"WHAT IS GOING ON HERE?!" you will probably ask. Nothing complex.
Function that is passed as argument accepts one or more arguments: first is a full match and the others are captured groups. It should return the string, that should replace the full match.
In our regular expression we described that we want to match all possible substrings in format \$\(([^)]+)\), where [^)]+ refers to one-or-more-of-any-symbols-except-a-closing-bracket, and this construction should be captured (it is between not-sanitized brackets).
So, once this regexp will match, it will pass the whole $(...) construction into match argument of passed function, and the name of the template into capture argument. So capture is our key for some data storage and we just returning this value in the function.
That's it! Hope, this will be helpful :)
You can use a simple function to make the substitution. Match every $(string) and apply a function to replace it with a variable stored in an object. Easy and extensible.
const tpl = '<div class="$(unique-result) single-result data-index=$(i)"><div class="airport-data data-index=$(i)">$(name)<br>$(city) ,$(country)</div><div class="airport-code data-index=$(i)">$(IATA)</div></div>';
const vars = {
i : 9,
'unique-result' : 'uniq',
country : 'gb',
city : 'Manchester',
IATA : 'MCH'
};
const replaceVars = (tpl,vars) => {
const replacer = (m, m1) =>
typeof vars[m1] != 'undefined' ? vars[m1] : '';
return tpl.replace(/\$\(([\w-]+)\)/g, replacer);
};
console.log(replaceVars(tpl,vars));
As a follow up to this question (not by me), I need to replace leading numbers of an id with \\3n (where n is the number we're replacing).
Some examples:
"1foo" -> "\\31foo"
"1foo1" -> "\\31foo1"
"12foo" -> "\\31\\32foo"
"12fo3o4" -> "\\31\\32fo3o4"
"foo123" -> "foo123"
Below is a solution that replaces every instance of the number, but I don't know enough regex to make it stop once it hits a non-number.
function magic (str) {
return str.replace(/([0-9])/g, "\\3$1");
}
... Or is regex a bad way to go? I guess it would be easy enough to do it, just looping over each character of the string manually.
Here is a way to achieve what you need using a reverse string + look-ahead approach:
function revStr(str) {
return str.split('').reverse().join('');
}
var s = "12fo3o4";
document.write(revStr(revStr(s).replace(/\d(?=\d*$)/g, function (m) {
return m + "3\\\\";
}))
);
The regex is matching a number that can be followed by 0 or more numbers only until the end (which is actually start) of a reversed string (with \d(?=\d*$)). The callback allows to manipulate the match (we just add reversed \\ and 3. Then, we just reverse the result.
Just use two steps: first find the prefix, then operate on its characters:
s.replace(/^\d+/, function (m) {
return [].map.call(m, function (c) {
return '\\3' + c;
}).join('');
});
No need to emulate any features.
Here is how I would have done it:
function replace(str) {
var re = /^([\d]*)/;
var match = str.match(re)[0];
var replaced = match.replace(/([\d])/g, "\\3$1");
str = str.replace(match, replaced);
return str;
}
document.write(replace("12fo3o4"));
Don't get me wrong: the other answers are fine! My focus was more on readability.
I would imagine this is a multiple part situation with regex, but how would you split a camelcase string at the capital letters turning them in to lowercase letters, and then adding a hyphen between each new string?
For example:
thisString
would become:
this-string
Try something like:
var myStr = 'thisString';
myStr = myStr.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
Late to answer, but this solution will work for cases where a single letter is camel cased.
'thisIsATest'.replace(/([a-zA-Z])(?=[A-Z])/g, '$1-').toLowerCase(); // this-is-a-test
Try the following:
var token = document.getElementsByTagName('strong')[0].innerHTML,
replaced = token.replace(/[a-z][A-Z]/g, function(str, offset) {
return str[0] + '-' + str[1].toLowerCase();
});
alert(replaced);
Example - http://jsfiddle.net/7DV6A/2/
Documentation for the string replace function:
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/replace
String.prototype.camelCaseToDashed = function(){
return this.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
}
// Usage
"SomeVariable".camelCaseToDashed();
I don't know why all these solutions are so complex but i simply found this to be enough:
function camelCaseToDash(input){
// replace Capital letter with the letter + a dash: '-', then lowercase everything.
return input.replace(/([A-Z])/g, '-$1').toLowerCase();
}
//or, using a callback function, directly lowercasing.
function camelCaseToDashCallback(input){
//replace capital letter with lowercase variant + a dash '-'.
return input.replace(/([A-Z])/g, (x)=> "-"+ x.toLowerCase());
}
generally option 1 is faster though: https://jsfiddle.net/4557z/17/
Anyone have a regex in javascript for converting:
someCamelCase into some-file-case
or
SomeCamelCase into some-file-case
??
If so, that would be very helpful.
Thanks.
You can make a simple regexp to capture a lowercase letter contiguous to an uppercase one, insert a dash between both and make the result all lowercase.
For example:
function fileCase(str) {
return str.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase();
}
fileCase('SomeCamelCase'); // "some-camel-case"
fileCase('someCamelCase'); // "some-camel-case"
Here. try this one.
"SomeCamelCase".replace(/[A-Z]/g, function(m){return '_' + m.toLowerCase();});
or as a function
function camelToHiphen(str){
return str.replace(/[A-Z]/g, function(m){return '_' + m.toLowerCase();});
}
Camel Case <=> Hyphen Case Conversion Methods:
disclaimer : I do not condone
clobbering the String prototype in the
way that I have below.
This is a prototype method on string for doing camelCase to hyphen-case that will account for uppercase beginning characters.
String.prototype.camelToHyphen = function() {
return this.replace(/((?!^)[A-Z])/g, '-$1').toLowerCase();
};
This solution was brought on by my search for the exact opposite.
String.prototype.hyphenToCamel = function() {
return (/-[a-z]/g.test(this)) ? this.match(/-[a-z]/g).map(function(m, n){
return m.replace(n, n.toUpperCase()[1]);
}, this) : this.slice(0);
};
I figure these are common enough issues but I could not find anything immediately that summed them up in this way.