如何洗掉陣列中的某些特定字符?例如;
var wording = ["She", "gives","me", "called", "friend"];
var suffix = ["s", "ed", "ing"];
function p {
return wording.substring(wording.substring(wording) - 1, wording.length - 1))
}
var text = wording.map(p);
console.log(text);
- 我想洗掉“gives”中的“s”,但不想洗掉“She”中的“S”。
- 我也想洗掉“被稱為”這個詞中的“ed”。
uj5u.com熱心網友回復:
如果其中一個單詞在endsWith其中一個字串上迭代,您可以切出找到的后綴的長度。
var wording = ["She", "gives","me", "called", "friend"];
var suffix = ["s", "ed", "ing"];
const p = word => {
const foundSuffix = suffix.find(str => word.endsWith(str));
return !foundSuffix ? word : word.slice(0, -foundSuffix.length);
}
var text = wording.map(p);
console.log(text);
另一種方法,使用正則運算式:
const wording = ["She", "gives","me", "called", "friend"];
const suffix = ["s", "ed", "ing"];
const pattern = new RegExp(suffix.join('|') '$');
const p = word => word.replace(pattern, '');
console.log(wording.map(p));
uj5u.com熱心網友回復:
方法一
var wording = ["She", "gives","me", "called", "friend"];
var suffix = ["s", "ed", "ing"];
function p(w) {
var ret = w;
suffix.forEach(s => {
if( w.endsWith(s) ) {
ret = ret.slice(0,w.length - s.length);
}
})
return ret
}
var text = wording.map(p);
console.log(text);
方法二
var wording = ["She", "gives","me", "called", "friend"];
var suffix = ["s", "ed", "ing"];
var text = wording
//check if any of the words end with any of the suffices min 0, max 1
.map(w => [w,suffix.filter(s => w.endsWith(s))])
//use the returned array to remove suffix, if found
.map(([w,s]) => s.length ? w.slice(0,w.length - s[0].length) : w);
console.log(text);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/368775.html
標籤:javascript 数组
上一篇:查找連續數字N次的頻率
下一篇:在圓形二維陣列中查找支點
