Javascript 如何将“camelCase”转换为“CamelCase”?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4149276/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 11:07:24  来源:igfitidea点击:

How to convert "camelCase" to "Camel Case"?

javascriptregex

提问by A Wizard Did It

I've been trying to get a JavaScript regex command to turn something like "thisString"into "This String"but the closest I've gotten is replacing a letter, resulting in something like "Thi String"or "This tring". Any ideas?

我一直在尝试使用 JavaScript 正则表达式命令将类似的内容"thisString"转换为,"This String"但我得到的最接近的是替换一个字母,从而产生类似"Thi String""This tring". 有任何想法吗?

To clarify I can handle the simplicity of capitalizing a letter, I'm just not as strong with RegEx, and splitting "somethingLikeThis"into "something Like This"is where I'm having trouble.

为了澄清我可以处理一个大写字母的简单,我只是不与正则表达式强,拆分"somethingLikeThis""something Like This"是在那里我遇到麻烦了。

回答by Vincent Robert

"thisStringIsGood"
    // insert a space before all caps
    .replace(/([A-Z])/g, ' ')
    // uppercase the first character
    .replace(/^./, function(str){ return str.toUpperCase(); })

displays

显示

This String Is Good

(function() {

  const textbox = document.querySelector('#textbox')
  const result = document.querySelector('#result')
  function split() {
      result.innerText = textbox.value
        // insert a space before all caps
        .replace(/([A-Z])/g, ' ')
        // uppercase the first character
        .replace(/^./, (str) => str.toUpperCase())
    };

  textbox.addEventListener('input', split);
  split();
}());
#result {
  margin-top: 1em;
  padding: .5em;
  background: #eee;
  white-space: pre;
}
<div>
  Text to split
  <input id="textbox" value="thisStringIsGood" />
</div>

<div id="result"></div>

回答by Matt Wiebe

I had an idle interest in this, particularly in handling sequences of capitals, such as in xmlHTTPRequest. The listed functions would produce "Xml H T T P Request" or "Xml HTTPRequest", mine produces "Xml HTTP Request".

我对此有兴趣,尤其是在处理大写字母序列方面,例如在 xmlHTTPRequest 中。列出的函数会产生“Xml HTTP 请求”或“Xml HTTPRequest”,我的会产生“Xml HTTP 请求”。

function unCamelCase (str){
    return str
        // insert a space between lower & upper
        .replace(/([a-z])([A-Z])/g, ' ')
        // space before last upper in a sequence followed by lower
        .replace(/\b([A-Z]+)([A-Z])([a-z])/, ' ')
        // uppercase the first character
        .replace(/^./, function(str){ return str.toUpperCase(); })
}

There's also a String.prototype version in a gist.

gist 中还有一个 String.prototype 版本。

回答by PleaseStand

This can be concisely done with regex lookahead (live demo):

这可以通过 regex lookahead ( live demo)简洁地完成:

function splitCamelCaseToString(s) {
    return s.split(/(?=[A-Z])/).join(' ');
}

(I thought that the g(global) flag was necessary, but oddly enough, it isn't in this particular case.)

(我认为g(全局)标志是必要的,但奇怪的是,它不是在这种特殊情况下。)

Using lookahead with splitensures that the matched capital letter is not consumed and avoids dealing with a leading space if UpperCamelCase is something you need to deal with. To capitalize the first letter of each, you can use:

split如果您需要处理 UpperCamelCase,则使用 Lookahead with可确保不消耗匹配的大写字母并避免处理前导空格。要将每个字母的首字母大写,您可以使用:

function splitCamelCaseToString(s) {
    return s.split(/(?=[A-Z])/).map(function(p) {
        return p.charAt(0).toUpperCase() + p.slice(1);
    }).join(' ');
}

The maparray method is an ES5 feature, but you can still use it in older browsers with some code from MDC. Alternatively, you can iterate over the array elements using a forloop.

map阵列方法是ES5功能,但你仍然可以使用它在旧的浏览器从MDC一些代码。或者,您可以使用循环遍历数组元素for

回答by thegreenpizza

I think this should be able to handle consecutive uppercase characters as well as simple camelCase.

我认为这应该能够处理连续的大写字符以及简单的驼峰式。

For example: someVariable => someVariable, but ABCCode != A B C Code.

例如:someVariable => someVariable,但 ABCCode != ABC Code。

The below regex works on your example but also the common example of representing abbreviations in camcelCase.

下面的正则表达式适用于您的示例,也是在 camcelCase 中表示缩写的常见示例。

"somethingLikeThis"
    .replace(/([a-z])([A-Z])/g, ' ')
    .replace(/([A-Z])([a-z])/g, ' ')
    .replace(/\ +/g, ' ') => "something Like This"

"someVariableWithABCCode"
    .replace(/([a-z])([A-Z])/g, ' ')
    .replace(/([A-Z])([a-z])/g, ' ')
    .replace(/\ +/g, ' ') => "some Variable With ABC Code"

You could also adjust as above to capitalize the first character.

您也可以按上述方式调整以大写第一个字符。

回答by kennebec

function spacecamel(s){
    return s.replace(/([a-z])([A-Z])/g, ' ');
}

spacecamel('somethingLikeThis')

spacecamel('somethingLikeThis')

// returned value: something Like This

// 返回值:像这样的东西

回答by Lawrence Chang

Lodashhandles this nicely with _.startCase()

Lodash很好地处理了这个问题_.startCase()

回答by SamGoody

A solution that handles numbers as well:

一个处理数字的解决方案:

function capSplit(str){
   return str.replace
      ( /(^[a-z]+)|[0-9]+|[A-Z][a-z]+|[A-Z]+(?=[A-Z][a-z]|[0-9])/g
      , function(match, first){
          if (first) match = match[0].toUpperCase() + match.substr(1);
          return match + ' ';
          }
       )
   }

Tested here [JSFiddle, no library.Not tried IE]; should be pretty stable.

在这里测试 [JSFiddle,没有库。没试过IE]; 应该很稳定。

回答by Daniel Fernández Espinoza

If you don't care about older browsers (or don't mind using a fallback reducefunction for them), this can split even strings like 'xmlHTTPRequest' (but certainly the likes of 'XMLHTTPRequest' cannot).

如果您不关心旧浏览器(或者不介意为它们使用回退reduce函数),这甚至可以拆分像 'xmlHTTPRequest' 这样的字符串(但肯定不能像 'XMLHTTPRequest' 这样的字符串)。

function splitCamelCase(str) {
        return str.split(/(?=[A-Z])/)
                  .reduce(function(p, c, i) {
                    if (c.length === 1) {
                        if (i === 0) {
                            p.push(c);
                        } else {
                            var last = p.pop(), ending = last.slice(-1);
                            if (ending === ending.toLowerCase()) {
                                p.push(last);
                                p.push(c);
                            } else {
                                p.push(last + c);
                            }
                        }
                    } else {
                        p.push(c.charAt(0).toUpperCase() + c.slice(1));
                    }
                    return p;
                  }, [])
                  .join(' ');
}

回答by pykiss

My version

我的版本

function camelToSpace (txt) {
  return txt
    .replace(/([^A-Z]*)([A-Z]*)([A-Z])([^A-Z]*)/g, '  ')
    .replace(/ +/g, ' ')
}
camelToSpace("camelToSpaceWithTLAStuff") //=> "camel To Space With TLA Stuff"

回答by M3ghana

Try this solution here -

在这里尝试这个解决方案 -

var value = "myCamelCaseText";
var newStr = '';
for (var i = 0; i < value.length; i++) {
  if (value.charAt(i) === value.charAt(i).toUpperCase()) {
    newStr = newStr + ' ' + value.charAt(i)
  } else {
    (i == 0) ? (newStr += value.charAt(i).toUpperCase()) : (newStr += value.charAt(i));
  }
}
return newStr;