我有一個文本框,里面有許多不同的文本行。我想將包含特定區分大小寫關鍵字的任何行移動到整個文本框的頂部或底部。我怎樣才能做到這一點?
示例輸入:
鮑勃喜歡葡萄,但不喜歡橙子。
約翰喜歡蘋果,但不喜歡梨。
帕特里克喜歡橙子,但不喜歡蘋果。
喬喜歡梨,但不喜歡橘子。
所需演算法:如果行包含“APPLES”或“ORANGES”,則移動到文本的頂部或底部。
示例輸出:
鮑勃喜歡葡萄,但不喜歡橙子。
喬喜歡梨,但不喜歡橘子。
約翰喜歡蘋果,但不喜歡梨。
帕特里克喜歡橙子,但不喜歡蘋果。
uj5u.com熱心網友回復:
const textarea = document.querySelector('textarea');
const AllLines = textarea.value.split("\n").filter(line => line!= '');
const linesWithApplesOranges = AllLines.filter(line => line.includes('APPLES') || line.includes('ORANGES'));
const linesWithoutApplesOranges = AllLines.filter(line => !line.includes('APPLES') && !line.includes('ORANGES'));
const newValue = [...linesWithoutApplesOranges, ...linesWithApplesOranges];
textarea.value = newValue.join("\n");
<textarea>
Bob likes GRAPES but not oranges.
John likes APPLES but not pears.
Patrick likes ORANGES but not apples.
Joe likes PEARS but not oranges.
</textarea>
uj5u.com熱心網友回復:
如果我正確理解您的條件,這應該可行。
let lines = [
'Bob likes GRAPES but not oranges.',
'John likes APPLES but not pears.',
'Patrick likes ORANGES but not apples.',
'Joe likes PEARS but not oranges.'
];
let output = [];
let top_or_bottom = [];
for (let i in lines) {
let line = lines[i];
// check if we have any of the keywords
let applesIndex = line.indexOf('APPLES');
let orangesIndex = line.indexOf('ORANGES');
// if we have, save it for later
if (applesIndex > -1) {
top_or_bottom.push(line);
} else if (orangesIndex > -1) {
top_or_bottom.push(line);
} else {
// otherwise push it into regular array
output.push(line);
}
}
// if moving to the bottom
output = output.concat(top_or_bottom);
// if moving to the top
// output = top_or_bottom.concat(output);
uj5u.com熱心網友回復:
如果您需要,我可以解釋解決方案
function modifyText() {
const triggerWords = ['apple', 'orange']
const textBox = document.getElementById('sampletext');
const lines = textBox.value.split('\n').filter(a => a.trim().length > 0);
const isTrigger = (s) => {
return !!triggerWords.find(x => s.includes(x));
};
lines.sort((a, b) => {
const aSmall = a.toLowerCase();
const bSmall = b.toLowerCase();
return isTrigger(aSmall) ?
isTrigger(bSmall) ? 0 : 1 :
isTrigger(bSmall) ? -1 : 0;
});
textBox.value = lines.join('\n');
}
<textarea id="sampletext" rows="12" cols="80">Some apples
some oranges
some things
some other stuff
Maybe apple maybe watermelon
</textarea>
<br/>
<button onClick="modifyText()">Click Me!</button>
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/503673.html
標籤:javascript
下一篇:單擊圖示時顯示和隱藏移動選單
