如何在给定序列中找到字符串并将整个序列复制到另一个文本字段?

问题描述 投票:0回答:1

我需要在textarea中找到给定的序列并将其复制到另一个字段。例如,我的输入和textarea将是这样的:

输入:CGGGAGGAA Texarea: @ M04644:45:147451:110237731 AGGGCGATGTCCTGGGATACGCGGGTGTCACGGGAGGAACCTGATCTGCCCAAATCTG + 11> 1AD DAC333EFFAFGGGGCC9A-9; A9-AAFB - 99- @ A9 - /;?/ B / ;: @ a0add382:1aaaa1:11023:24dsa31 AGGGCGATGTCCTGGGATACGCGGGTGTCATATGCCTTCCTGATCTGCCCAACCATCTG + 11> 1AD DAC333EFFAFGGGGCC9A-9; A9-AAFB - 99- @ A9 - /;?/ B / ;: 。 。 。

这段文字一直在继续。现在我想从textarea值中找到所有CGGGAGGAA序列并推送前一行,该行包含CGGGAGGAA,后两行包含第二个textarea。所以我的第二个区域是这样的:

@ a0add382:1aaaaa1:11023:24dsa31 AGGGCGATGTCCTGGGATACGCGGGTGTCATATGCCTTCCTGATCTGCCCAACCATCTG + 11> 1 FROM?DATZZEFEFFGGGTYa-I; A - I-AFB? - Yaya- @ Aya - /; / B / ;:

任何帮助深表感谢。提前致谢。

document.getElementById('search').addEventListener('click', stringSearch);

function stringSearch() {
    var searchSequence = document.getElementById('searchSequence').value;
    var text = document.getElementById('text').value;
    var result = [];
    
    if(searchSequence.length > 0 && text.includes(searchSequence)) {
        alert("found");
    } else {
        alert("Not found");
    }
} 
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <input id="searchSequence" type="text"> <br>
    <br>
    <textarea id="text" name="" id="" cols="30" rows="10" wrap="off">

    </textarea> <br>

    <textarea name="" id="copy" cols="30" rows="10" wrap="off"></textarea> <br>
    
    <button type="button" id="search">Search</button>

    <script src="main.js"></script>
</body>
</html>
javascript html html5
1个回答
0
投票

在行尾字符上拆分输入文本

搜索每一行

如果找到,请将适当的值推送到数组

document.getElementById('search').addEventListener('click', stringSearch);

function stringSearch() {
  const searchSequence = document.getElementById('searchSequence').value;
  const text = document.getElementById('text').value;
  const dest = document.getElementById('copy');
  const lines = text.split(/\r?\n/g);
  const result = lines.flatMap((line, i) => line.includes(searchSequence) ? lines.slice(i-1, i+3) : []);
  
  if (result.length) {
    dest.value = result.join('\n');
  } else {
    dest.value="**not found**";
  }
}
<input id="searchSequence" type="text"> <br>
<br>
<textarea id="text" cols="30" rows="10" wrap="off"></textarea>
<br/><br/>
<textarea id="copy" cols="30" rows="10" wrap="off"></textarea>
<br/>
<button type="button" id="search">Search</button>
© www.soinside.com 2019 - 2024. All rights reserved.