用于搜索字符串并支持所有大写标记的JavaScript

时间:2013-08-26 07:11:13

标签: javascript regex

我需要JavaScript来搜索字符串以查找所有大写的标记,不包括第一个标记,并用括号标记替换所有标记。

E.g。

"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"

1 个答案:

答案 0 :(得分:1)

您可以使用$&。来替换替换use a matched string 另外,\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}'