【问题标题】:JavaScript - check string for substring and capitalize substring [closed]JavaScript - 检查字符串的子字符串并将子字符串大写[关闭]
【发布时间】:2020-07-28 03:23:01
【问题描述】:
我将如何测试一个字符串以查看它是否包含特定的子字符串,然后将该子字符串大写?
var string = " A Fine and Rare George Iii Neoclassical Ormolu Urn Clock"
找到罗马数字并将其大写为 III。
另一个例子:
var string2 = "Platinum Pf00673"
在包含数字的字符串中查找并大写字母,所以上面变成PF00673
【问题讨论】:
标签:
javascript
regex
string
【解决方案1】:
您可以使用对String#replace 的回调。
var string2 = "Platinum Pf00673";
var result = string2.replace(/\w*[0-9]\w*/g, match=>match.toUpperCase());
console.log(result);
【解决方案2】:
使用正则表达式进行匹配和替换。
var string2 = "Platinum Pf00673"
var reg = new RegExp("[A-Z]+[0-9]+[A-Z0-9]+", "gi");
var matches = string2.matchAll(reg);
for(var match of matches)
{
var parts = string2.split("");
parts.splice(match.index, match[0].length, ...match[0].toUpperCase().split(""));
string2 = parts.join("");
}
console.log(string2);
【解决方案3】:
一个简单的解决方案是像这样创建一个辅助函数
const capitlizeSubStr = (string, substring) => {
const regex = new RegExp(substring, 'gi')
const newString = string.replace(regex, substring.toUpperCase())
return newString
}
【解决方案4】:
回答罗马数字问题。
var string1 = "A Fine and Rare George Iii Neoclassical Ormolu Urn Clock";
var result = string1.replace(/M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})/ig, match=>match.toUpperCase());
console.log(result);
这是 hev1 答案的扩展。
【解决方案5】:
大写罗马字:
'world war Iii'.replace(/\w+/g, word => word.match(/^[MCDXVI]+$/i) ? word.toUpperCase() : word)
// "world war III"
用数字大写单词
'Platinum Pf00673'.replace(/\w+/g, word => word.match(/\d/) ? word.toUpperCase() : word)
// "Platinum PF00673"