简体   繁体   中英

Javascript Regex - Camel to File Case

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM