我需要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"
答案 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}'