我试图在句子中找到严格声明的字符串,线程说:
Find the position of the string "ten" within a sentence, without using the exact string directly (this can be avoided in many ways using just a bit of RegEx). Print as many spaces as there were characters in the original sentence before the aforementioned string appeared, and then the string itself in lowercase.
我已经走到这一步了:
let words = 'A ton of tunas weighs more than ten kilograms.'
function findTheNumber(){
let regex=/t[a-z]*en/gi;
let output = words.match(regex)
console.log(words)
console.log(output)
}
console.log(findTheNumber())
结果应该是:
input = A ton of tunas weighs more than ten kilograms.
output = ten(ENTER)
最佳答案
您可以在回调函数的帮助下尝试正则表达式替换方法:
var input = "A ton of tunas weighs more than ten kilograms.";
var output = input.replace(/\w+/g, function(match, contents, offset, input_string)
{
if (!match.match(/^[t][e][n]$/)) {
return match.replace(/\w/g, " ");
}
else {
return match;
}
});
console.log(input);
console.log(output);
上述逻辑匹配输入句子中的每个单词,然后有选择地将每个不是 10
的单词替换为相同数量的空格。
关于javascript - 正则表达式匹配句子中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69166064/