首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何获取行号及其文本,如果找到关键字

如何获取行号及其文本,如果找到关键字
EN

Stack Overflow用户
提问于 2021-04-17 14:10:57
回答 2查看 84关注 0票数 0

我有一个HTML表单,它将用户输入到文本框中,比如“发现”,然后从“Textarea”框中打印带有文本的行号

Html代码:

代码语言:javascript
复制
<div>search</div>
<input type="text" id="needle" value="throw">
<div>this text</div>
<textarea id="haystack">Twenty years from now
you will be more disappointed 
by the things that you didn't 
do than by the ones you did do, 
so throw off the bowlines, 
sail away from safe harbor, 
catch the trade winds in your 
sails. Explore, Dream, Discover. 
    —Mark Twain
</textarea>
<input type="submit" value="Check" onClick="searchText()"> <br><br>
<div>results</div>
<textarea id="output"></textarea>

Javascript :

代码语言:javascript
复制
function searchText(){
// If you want to find the line number for a specific match you need to know it index
    function lineNumberByIndex(index,string){
        // RegExp
        var line = 0,
            match,
            re = /(^)[\S\s]/gm;
        while (match = re.exec(string)) {
            if(match.index > index)
                break;
            line++;
        }
        return line;
    }
    // if you want to find the first index of a match
    function lineNumber(needle,haystack){
        return lineNumberByIndex(haystack.indexOf(needle),haystack);
    }
    // if you want an array of matches
    function lineNumbers(needle,haystack){
        if(needle !== ""){
            var i = 0,a=[],index=-1;
            while((index=haystack.indexOf(needle, index+1)) != -1){
                a.push(lineNumberByIndex(index,haystack));
            }
            return a;
        }
    }
    function update(){
        var needle = $('#needle').val();
        var haystack = $('#haystack').val();
        var output = $("#output").val();
        var nums = lineNumbers(needle,haystack);
        var s = "\"" + needle + "\" is on lines " + nums.join(',') + "\n";
        if(nums.length)
            $("#output").val(s + output);
        else
            $("#output").val("-\n" + output);
    }
    $("input,textarea.input").on("input",update);
    update()
}

.css

代码语言:javascript
复制
* {font:1em arial}
input {width:400px;;padding:5px}
textarea {width:400px;height:200px;padding:5px;}

我必须通过创建按钮点击调用,但它会打印异常文本,如果我删除搜索文本并重新输入任何其他文本按钮上单击文本出现的次数为n次

如何编写可以搜索文本并打印行号和文本的代码

代码摘自此处: http://jsfiddle.net/pcmxw37d/

异常输出:

代码语言:javascript
复制
"harbor" is on lines 6
"harbor" is on lines 6
"harbor" is on lines 6
"harbor" is on lines 6
"harbor" is on lines 6
"harbor" is on lines 6
"harbor" is on lines 6
"harbor" is on lines 6
"harbor" is on lines 6
"harbor" is on lines 6
"harbor" is on lines 6
"harbor" is on lines 6
"harbor" is on lines 6
"harbor" is on lines 6
"harbor" is on lines 6
EN

回答 2

Stack Overflow用户

发布于 2021-04-17 14:38:44

下面是一个简单的示例(也适用于区分大小写的):

代码语言:javascript
复制
const EL_searchField  = document.querySelector("#searchField");
const EL_searchArea   = document.querySelector("#searchArea");
const EL_searchResult = document.querySelector("#searchResult");  
const EL_searchButton = document.querySelector("#searchButton");


const search = () => {
  const val = EL_searchField.value.trim(); // Does exactly what it says
  const txt = EL_searchArea.value.trim();  // Does exactly what it says
  // Split lines and get them all as <div> Strings into an Array by using .reduce()
  const result = txt.split(/\n/).reduce((arr, line, i) => {
    if (line.toLowerCase().includes(val.toLowerCase())) {
      arr.push(`<div class="flex"><i>Line ${i+1}:</i><span>${(line.replace(new RegExp(val, "ig"), "<b>$&</b>"))}</span></div>`);
    }
    return arr;
  }, []);
  // If no txt or no val: use an empty String ""
  // else, join our array of <div>s into a single String of HTML <div>s  
  EL_searchResult.innerHTML = (!val || !txt) ? "" : result.join("");
};

EL_searchField.addEventListener("input", search);
EL_searchArea.addEventListener("input", search);
EL_searchButton.addEventListener("click", search);
search();
代码语言:javascript
复制
* { margin: 0; box-sizing: border-box; }
body { font: 14px/1.4 sans-serif; }

.flex { display: flex; }
#searchArea { width: 400px; max-width: 50%; height: 160px; }
#searchResult div { gap: 10px; }
#searchResult i   { opacity: 0.5; white-space: nowrap;}
#searchResult b   { color: blue;}
代码语言:javascript
复制
<label><input type="text" id="searchField" placeholder="Search text..."></label>
<button type="button" id="searchButton">SEARCH</button>

<div class="flex">
<textarea id="searchArea">Twenty years from now
you will be more disappointed 
by the things that you didn't 
do than by the ones you did do, 
so throw off the bowlines, 
sail away from safe harbor, 
catch the trade winds throw in your 
sails. Explore, Dream, Discover.
    —Mark Twain</textarea>
<div id="searchResult"></div>
</div>

票数 3
EN

Stack Overflow用户

发布于 2021-04-17 14:18:15

您可以使用.textContent获取文本,并使用split('\n')获取数组中的每一行。然后,获取数组的长度。.split('\n')在结尾处返回一个额外的字符串,所以您必须忽略它

代码语言:javascript
复制
document.querySelector('#haystack').textContent.split('\n')

您需要在事件侦听器中运行该行,以便它总是更新。

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67139092

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档