6

我想在一个字符串中的小写和大写之间添加一个空格。例如:

FruityLoops
FirstRepeat

现在我想在小写字母和大写字母之间添加一个空格。我不知道我应该如何开始使用 JavaScript。与 substr 或搜索有关的东西?有人可以帮助我吗?

4

4 回答 4

21
var str = "FruityLoops";

str = str.replace(/([a-z])([A-Z])/g, '$1 $2');

示例:http: //jsfiddle.net/3LYA8/

于 2011-01-27T17:43:15.910 回答
3

像这样简单的事情:

"LoL".replace(/([a-z])([A-Z])/g, "$1 $2")

可能就足够了;)

于 2011-01-27T17:43:59.637 回答
2

您可以通过手动搜索来完成,但使用正则表达式可能更容易。假设:

  • 你知道它以大写字母开头
  • 你不想在那个首都前面有一个空间
  • 您想要在所有后续大写字母前面有一个空间

然后:

function spacey(str) {  
    return str.substring(0, 1) +
           str.substring(1).replace(/[A-Z]/g, function(ch) {
        return " " + ch;
    });
}

alert(spacey("FruitLoops")); // "Fruit Loops"

活生生的例子

受(但不同于)帕特里克的回答启发的更有效的版本:

function spacey(str) {  
    return str.substring(0, 1) +
           str.substring(1).replace(/([a-z])?([A-Z])/g, "$1 $2");
}

alert(spacey("FruityLoops"));  // "Fruity Loops"
alert(spacey("FruityXLoops")); // "Fruity X Loops"

活生生的例子

于 2011-01-27T17:44:06.797 回答
0

regexp 选项看起来最好。不过,让正则表达式正确似乎很棘手。

这里还有一个问题,需要尝试一些更复杂的选项:

正则表达式,用大写字母分割字符串但忽略 TLA

于 2011-01-27T18:08:48.500 回答