-1

I need JavaScript to search a string for all capitalized tokens, excluding the first, and replace all of the them with a bracketed token.

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

1 回答 1

1

您可以使用$& 在替换中使用匹配的字符串。
此外,\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}'
于 2013-08-26T07:31:06.150 回答