如果句子中的單詞也在陣列中,則取該單詞的前 3 個字母,并在末尾加上句點。
var arr = ['select', 'delete', 'Truncate', 'insert', 'update']
function checkValue(value, arr) {
var newText;
for (var i = 0; i < arr.length; i ) {
var name = arr[i];
if (value.toLowerCase().includes(name.toLowerCase())) {
newText = value.toLowerCase().replace(name, name.substring(0, 3));
break;
}
}
return newText;
}
console.log(checkValue('Hello Hello Delete33 Hello', arr));
它給了我:你好你好del33你好。
但我想要:你好,你好,德爾。你好。
uj5u.com熱心網友回復:
您可以arr在單詞邊界之后創建一個與您的專案匹配的正則運算式,并在它們之后使用任何單詞字符,并替換為前三個字符,然后在后面附加一個點:
var arr = ['select', 'delete', 'Truncate', 'insert', 'update']
var re = new RegExp("\\b(?:" arr.join('|') ")\\w*", 'ig')
function checkValue(value, re) {
return value.replace(re, (x) => x.substr(0,3) ".");
}
console.log(checkValue('Hello Hello Delete33 Hello', re));
// => Hello Hello Del. Hello
請參閱正則運算式演示。詳情:
\b- 單詞邊界(?:select|delete|Truncate|insert|update)- 匹配單詞之一的非捕獲組\w*- 零個或多個單詞字符(字母、數字、_)。
uj5u.com熱心網友回復:
var arr = ['select', 'delete', 'truncate', 'insert', 'update']
function checkValue(value, arr) {
return value.split(" ").map(x => arr.find(y => x.toLowerCase().includes(y)) ? x.substring(0, 3) "." : x).join(" ");
}
console.log(checkValue('Hello Hello Delete33 Hello', arr));
uj5u.com熱心網友回復:
關鍵是您獲得了子字串但保留了數字,而不是添加句號。
map這是使用、some和的替代方法join。
const arr = ['select', 'delete', 'Truncate', 'insert', 'update'];
function checkValue(value, arr) {
// `split` the string into words, and `map`
// over them
return value.split(' ').map(word => {
// If one of the lowercase words in the array
// is included included in the lowercase word...
const found = arr.some(el => {
return word
.toLowerCase()
.includes(el.toLowerCase());
});
// ...return the updated word
if (found) return `${word.slice(0, 3)}.`;
// Otherwise just return the word
return word;
// And `join` the array back to a string
}).join(' ');
}
const str = 'Hello Hello Delete33 Hello Truncate';
const out = checkValue(str, arr);
console.log(out);
附加檔案
- 模板/字串文字
uj5u.com熱心網友回復:
這非常有幫助和酷,非常感謝分享
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/471223.html
標籤:javascript 正则表达式
