Javascript string remove line if not includes

I am trying to get a code for a webpage using javascript. But I only want to return lines that include the word “array” How can I remove all lines that do not include “array?” I can’t find anything online and my skills are very basic.

“I type this sentence because it says the post is mostly a code, and it still says the same so I’m just extending this.”

function DOMtoString(document_root) {
    var sourcecode = '',
        node = document_root.firstChild;
    while (node) {
        switch (node.nodeType) {
        case Node.ELEMENT_NODE:
            sourcecode += node.outerHTML;
            break;
        case Node.TEXT_NODE:
            sourcecode += node.nodeValue;
            break;
        case Node.CDATA_SECTION_NODE:
            sourcecode += '<![CDATA[' + node.nodeValue + ']]>';
            break;
        case Node.COMMENT_NODE:
            sourcecode += '<!--' + node.nodeValue + '-->';
            break;
        case Node.DOCUMENT_TYPE_NODE:
            // (X)HTML documents are identified by public identifiers
            sourcecode += "<!DOCTYPE " + node.name + (node.publicId ? ' PUBLIC "' + node.publicId + '"' : '') + (!node.publicId && node.systemId ? ' SYSTEM' : '') + (node.systemId ? ' "' + node.systemId + '"' : '') + '>n';
            break;
        }
        node = node.nextSibling;
    } 
    
    var public = sourcecode.substring(
        sourcecode.lastIndexOf("'[[") + 1, 
        sourcecode.lastIndexOf("]]';")
        
    );

    var matematika = sourcecode.substring(
        sourcecode.lastIndexOf("var arraypaginascopia;") + 1, 
        sourcecode.lastIndexOf("var rellenado;")    
    );

    
    var test = ("testovaci zprava");
    var test2 = ("testovaci zprava druha");
    var fail = ("Internal Error");
    
    //arrayrespuestas
    
    var currenturl = document.URL;
    var url = currenturl.includes("www.liveworksheets.com/workbooks")
    //return url;
    
    if (url == true){
        return matematika;
    } else {
        return public; 
    }
For example:

This is an example

This is an example

This is an example

This is a banana

This is an example

This is an example

This is a banana




The result should be:

This is a banana

This is a banana

Answer

In your question, you asked for the word array, but I’ll use your example banana for the code.

const regex = /.*banana.*/gm;
// (.*) matches any character before and after the search string 'banana';
// The g flag is to match all occurrences and; 
// The m flag is for a multi-line string
    
const str = `This is an example

This is an example

This is an example

This is a banana

This is an example

This is an example

This is a banana`;

console.log(str.match(regex));

Leave a Reply

Your email address will not be published. Required fields are marked *