-1

我试图定位字符串中每个单词的第一个字母。我正在使用 JavaScript。我发现有关 Python 和 PHP 的讨论并没有解决我特定于 JavaScript 的问题。

str = "i'm a little tea pot"

regEx = /^.|\b[a-z]/g

我有一个函数将 regEx 找到的每个字母大写。我的结果是m撇号大写之后。我该如何避免这种情况?

大写函数后:I'M A Little Tea Pot"

4

2 回答 2

1

每个单词的首字母大写?

var string = prompt("Enter a string");

function capitalizeFirstWord(str) {
    return str.split(/\s+/).map(function(word) {
        return word[0].toUpperCase() + word.slice(1).toLowerCase();
    }).join(' ');
}

document.getElementById("capitalized").innerHTML =  capitalizeFirstWord(string);
<p id="capitalized"></p>

您在单词边界处拆分字符串。作为参数,您可以传入一个空字符串或空白字符\s。这将创建句子中所有单词的数组。

要获取第一个字符,您可以使用word[0]word.charAt(0)。然后,您对字符串的其余部分执行字符串连接。

这为您提供了一个全新的数组,需要将其转换回字符串。在这个新数组上调用 join 方法

于 2016-01-23T03:03:31.500 回答
1

您可以在str.replace.

var str = "i'm a little tea pot"
alert(str.replace(/(^|\s)([a-z])/g, function(match, group_1, group_2){return group_1 + group_2.toUpperCase()}))

而且,如果您想将第一个字符后面的字符转换为小写,请尝试此操作。

str.replace(/(^|\s)([a-z])(\S*)/g, function(x,y, z, a){return y + z.toUpperCase() + a.toLowerCase()})
于 2016-01-23T03:11:06.463 回答