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/
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 need to format a string for comparison purpose.
Lets say we have
Multiple Choice
I want to convert it to
multiplechoice
So white spaces removed, any special characters removed and lowercase.
I need to do this in SAPUI5 while comparing a value which I get from a model.
if (oCurrentQuestionModel.getProperty("/type") === "multiple choice")
How can I achieve this?
You can do it as:
var str = "Multiple Choice";
var strLower = str.toLowerCase();
strLower.replace(/\s/g, '');
Working demo.
The Regex
\s is the regex for "whitespace", and g is the "global" flag, meaning match all \s (whitespaces).
function cleaner(str) {
if (str) {
var strLower = str.toLowerCase();
return strLower.replace(/\W/g, '');
}
return false;
}
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"
I know how to find the first occurence of a predefined character like so a.indexOf("R") but what if you would like to find the first occurence of any character A-Z, say that my string contains digits and other special characters and I'm only interested in a "normal" letter?
use regex:
a.match(/[A-Za-z]/);
Use regex.
var a = " $#714 Abcd";
answer = a.match(/[A-Za-z]/)[0]
console.log(answer); // 'A'
You can use regex in order to match this expression:
a.match(/^[A-Za-z][A-Za-z0-9]*$/)
This will check whether the first character is alphabet and then the rest to be alphanumeric
This function will return an array with the positions in the string of all the first occurrence of any letter:
var s = 'asdlkn akn dlkandl nl ndvds';
function getFirstOccurrenceOffset(s) {
s = s.split("").reverse().join(""); // reverse the string
var re = /([A-Z])(?!.*\1)/gi;
var m;
var result = Array();
while ((m = re.exec(s)) !== null)
result.push(s.length - m.index - 1);
return result.reverse();
}
console.log(getFirstOccurrenceOffset(s));
The function is case insensitive, but you can remove the i modifier to make it case sensitive.
I am attempting to create a way to convert text with lowercase letters and underscores into text without underscores and the first letter of each word is capitalized.
ex;
options_page = Options Page
At this page: How to make first character uppercase of all words in JavaScript?
I found this regex:
key = key.replace(/(?:_| |\b)(\w)/g, function(key, p1) { return p1.toUpperCase()});
This does everything except replace the underscores with spaces. I have not really tried anything because I am not that familiar with regexpressions.
How can I adjust this regex so it replaces underscores with spaces?
This should do the trick:
function humanize(str) {
var i, frags = str.split('_');
for (i=0; i<frags.length; i++) {
frags[i] = frags[i].charAt(0).toUpperCase() + frags[i].slice(1);
}
return frags.join(' ');
}
console.log(humanize('humpdey_dumpdey'));
// > Humpdey Dumpdey
repl
http://repl.it/OnE
Fiddle:
http://jsfiddle.net/marionebl/nf4NG/
jsPerf:
Most test data: http://jsperf.com/string-transformations
All versions plus _.str: http://jsperf.com/string-transformations/3
Since Lodash 3.1.0, there's a _.startCase([string='']) method that transforms any case into capitalized words (start case):
_.startCase('hello_world'); // returns 'Hello World'
_.startCase('hello-world'); // returns 'Hello World'
_.startCase('hello world'); // returns 'Hello World'
There are other useful methods in the String section of Lodash. Read the documentation here.
These are two different tasks, so two different regexes is the best solution:
key = key.replace(/_/g, ' ').replace(/(?: |\b)(\w)/g, function(key) { return key.toUpperCase()});
To ensure even all capital words is processed. You can add .toLowerCase() before the very first .replace:
console.log('TESTING_WORD'.toLowerCase().replace(/_/g, ' ')
.replace(/(?: |\b)(\w)/g, function(key, p1) {
return key.toUpperCase();
}));
Simply add .replace('_',' ')
Like this
function toCamel(string){
return string.replace(/(?:_| |\b)(\w)/g, function($1){return $1.toUpperCase().replace('_',' ');});
}
Another alternative:
camel = "options_page".replace(/(^|_)(\w)/g, function ($0, $1, $2) {
return ($1 && ' ') + $2.toUpperCase();
});
console.log(camel);
The regular expression:
(^|_) beginning of the input OR "_" ($1)
(\w) a word character (short for [a-zA-Z0-9_]) ($2)
g all occurrences (global)
More about regular expressions : http://www.javascriptkit.com/javatutors/redev.shtml.
Here:
var str = 'Lorem_ipsum_dolor_sit_amet,_consectetur____adipiscing_elit.'
str = str.replace(/_{1,}/g,' ').replace(/(\s{1,}|\b)(\w)/g, function(m, space, letter)
{
return space + letter.toUpperCase();
})
console.log(str);