我一直试图得到一个JavaScript regex命令,把类似“thisString”的东西变成“This String”,但我得到的最接近的是替换一个字母,导致类似“This String”或“This String”的东西。什么好主意吗?

为了澄清我可以处理大写字母的简单性,我只是不太擅长RegEx,把“somethingLikeThis”分割成“somethingLikeThis”是我遇到麻烦的地方。


不是正则表达式,但知道这些简单而古老的技巧是有用的:

var origString = "thisString";
var newString = origString.charAt(0).toUpperCase() + origString.substring(1);

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

显示

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, ' $1') // 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>


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

spacecamel(“somethingLikeThis”)

//返回值:Like This


这可以用regex lookahead(现场演示)简单地完成:

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

(我认为g(全局)标志是必要的,但奇怪的是,在这个特定的情况下并不是这样。)

如果需要处理UpperCamelCase,那么使用ahead和split可以确保匹配的大写字母不会被消耗,并避免处理前导空格。要将每个字母的首字母大写,可以使用:

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

映射数组方法是ES5的一个特性,但是您仍然可以通过MDC的一些代码在旧的浏览器中使用它。或者,您可以使用for循环遍历数组元素。


我对此没什么兴趣,特别是在处理大写字母序列方面,比如xmlHTTPRequest。列出的函数会产生“Xml HTTPRequest”或“Xml HTTPRequest”,我的产生“Xml HTTPRequest”。

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

还有一个字符串。原型版本的一个要旨。


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

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 + ' ';
          }
       )
   }

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


如果你不关心旧的浏览器(或者不介意为它们使用回退减少函数),这甚至可以分割'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(' ');
}

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

例如:somvariable => somvariable, but ABCCode != ABCCode。

下面的正则表达式不仅适用于您的示例,还适用于camcelCase中表示缩写的常见示例。

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

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

你也可以如上调整第一个字符的大写。


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


我的版本

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

试试这个解决方案

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;

const value = 'camelCase';
const map = {};
let index = 0;
map[index] = [];
for (let i = 0; i < value.length; i++) {
  if (i !== 0 && value[i] === value[i].toUpperCase()) {
    index = i;
    map[index] = [];
  }
  if (i === 0) {
    map[index].push(value[i].toUpperCase());
  } else {
    map[index].push(value[i]);
  }
}
let resultArray = [];
Object.keys(map).map(function (key, index) {
  resultArray = [...resultArray, ' ', ...map[key]];
  return resultArray;
});
console.log(resultArray.join(''));