JavaScript来搜索字符串和大括号中的所有大写标记

JavaScript to search a string and brace all capitalzied tokens

本文关键字:搜索 字符串 JavaScript      更新时间:2023-09-26

我需要JavaScript在字符串中搜索所有大写的令牌,不包括第一个,并用括号中的令牌替换所有这些令牌。

例如

"Rose Harbor in Bloom: A Novel" -> "Rose {Harbor} in {Bloom}: {A} {Novel}"
"In America: a novel" -> "In {America}: a novel"
"What else. In the country" -> "What else. {In} the country"

您可以使用$&在替换中使用匹配的字符串
此外,'b指定单词边界,[A-Z]将指定所有大写字符
*?尝试使用尽可能少的字符进行匹配

所以你想要.replace(/'b[A-Z].*?'b/g, '{$&}')

举个例子:

"a String is Good yes?".replace(/'b[A-Z].*?'b/g, '{$&}')

返回

"a {String} is {Good} yes?"

对于exclude the first token,你必须有一点创造性;

function surroundCaps(str) {
    //get first word
    var temp = str.match(/^.+?'b/);
    //if word was found
    if (temp) {
        temp = temp[0];
        //remove it from the string
        str = str.substring(temp.length);
    }
    else
        temp = '';
    str = str.replace(/'b[A-Z].*?'b/g, '{$&}');
    return temp + str;
}
surroundCaps('String is Good Yes'); //'String is {Good} {Yes}'