简体   繁体   English

Javascript Regex - Camel to File Case

[英]Javascript Regex - Camel to File Case

Anyone have a regex in javascript for converting: 任何人都有javascript的正则表达式转换:

someCamelCase into some-file-case someCamelCase进入some-file-case

or 要么

SomeCamelCase into some-file-case SomeCamelCase进入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. 免责声明:我不会宽恕以下我的方式破坏String原型。

This is a prototype method on string for doing camelCase to hyphen-case that will account for uppercase beginning characters. 这是一个用于执行camelCase到字符串的字符串的原型方法,它将占用大写的起始字符。

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. 我认为这些是常见的问题,但我找不到任何立即以这种方式总结的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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