Locate specific phrases within the text and conceal the corresponding lines

I have a JavaScript function that loops through each line. I want it to search for specific text on each line and hide the entire line if it contains that text. For example:

  <input id="search" type="button" value="Run" />
      <textarea id="main" style="height:150px;">
       300 300 300
       300 200 300
       100 100 150
      </textarea>
    

Javascript

$('#search').bind('click', function () {
        var lines = $("#main").val().split("\n");
        for (var i = 0; i < lines.length; i++) {
            if($([i].contains('300' || '200'){
                $(lines).css('display','none');
            }
        }
    
    });
    

The code currently breaks the lines into 3 rows. However, how can I modify it to search for certain text within each row and hide those rows where the text is found, rather than just removing the number? So in the example above, the desired output would be:

    100 100 150
    

Answer №1

If you want to update the entire content of a textarea, you'll need to replace the entire value as there is no way to target individual lines within the text. You cannot hide or style specific lines in a textarea; it's all or nothing.

The code below filters out certain values from each line in the textarea and then joins the remaining lines back together with a line break as a delimiter:

$('#search').on('click', function() {
  $("#main").val(function(_, oldVal) {   
    return oldVal.split('\n').filter(function(str) {
      return str.indexOf('200') === -1 && str.indexOf('300')=== -1
    }).join('\n');
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="search" type="button" value="Run" />
<textarea id="main" style="height:150px;">
  300 300 300
  300 200 300 
  100 100 150
</textarea>

Answer №2

  <textarea id="main" style="height:150px;">
    200 100 300
    100 200 100
    200 200 150
  </textarea>




  <script>
  var text_not_allow = ["100", "200"];

  //in this section, we are taking the text content inside the HTML textarea element and performing some operations on it
  var text_area_array =document.getElementById('main').innerHTML.split('\n');
  var final_text = '';



  for (var i=0;i<text_area_array;i++)
  {

    var line=text_area_array[i];

    var line_allow=true;
    for (var j=0;j<text_remove;j++)
    {
        if (line.includes(text_remove[j]))
        {line_allow=false;}
      }
      if (line_allow){final_text+=line + '\n'};
   }
  document.getElementById('main').innerHTML=final_text;
  </script>

Answer №3

While not as polished as Charlies' solution, here is another approach:

$('#search').on('click', function () {
    var lines = $("#main").val().split("\n");
    var i = lines.length
    while (i--) {
        if( lines[i].indexOf('300') >-1 || lines[i].indexOf('200') > -1){
            lines.splice(i,1);
        }
    }
    var str = '';
    for (var i = 0; i < lines.length; i++) {
      str += lines[i] + "\n";
    }
    $('#main').val(str);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="search" type="button" value="Run" />
<textarea id="main" style="height:150px;">
  300 300 300
  300 200 300
  100 100 150
</textarea>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring how to integrate a jQuery ajax request within Javascript's XmlHttpRequest technique

My current setup involves an ajax call structured like this: var data = {"name":"John Doe"} $.ajax({ dataType : "jsonp", contentType: "application/json; charset=utf-8", data : JSON.stringify(data), success : function(result) { alert(result.success); // re ...

Drop the <span> element into a paragraph by utilizing JQuery's drag and drop feature

Trying to drag and drop <span> into <p>. The code is functional, but encountering 3 issues: When editing content inside <p> by typing (e.g. three words) and then dragging <span> into <p>, the newly typed words are consider ...

What is the best way to combine PHP with HTML in your code?

I am looking to display data from a database in a table format. Additionally, I want to include images sourced from the same database. Using AJAX, I have a function called getPosts that fetches data from getPosts.php and populates a table with it. Althou ...

Obtaining the Author's ID on Blogger

Is there a way to extract the author's ID on Google's blogger.com platform? I'm familiar with how to obtain the post ID using data:post.id, but what about the author's ID? ...

Troubleshooting the Vue.js component rendering issue

I am trying to display only one object from the data on firebase using [objectNumber]. I want to show {{ligler[1].name}} in the template, but it is causing errors: Error when rendering component Uncaught TypeError: Cannot read property 'name' o ...

Prevent Hover Effects When Clicked

I am working on a project where I have a div containing an unordered list that moves to the left when you click on an LI item. <div id="products"> <ul> <li><a href="">Product 1</a></li> <li><a href="">Produc ...

What is the best method to send a HTTP request (specifically for scraping) to an Angular2 website?

I am attempting to utilize a node server to extract data from an angular2 application. However, the issue I am encountering is that the response I receive is just the index.js file, which essentially represents the "loading..." section of the webpage. My ...

The functionality of selecting all items in v-select does not result in saving all of them

I'm currently working on integrating a select all button into the v-select component of Vuetify. The issue I am facing is that even though I can use the button to select all options, when I attempt to save, not all items are saved. However, if I manua ...

A complete guide on utilizing *ngFor in Angular to display data rows

I am facing an issue with using *ngFor to create new "rows" for adding new categories dynamically. Although there are no errors displayed when I run the program, the intended functionality is not achieved. I have tried making some modifications but it see ...

Are your GetJSON requests failing to execute properly?

I have a code snippet that executes in a certain sequence and performs as expected. <script> $.getJSON(url1, function (data1) { $.getJSON(url2, function (data2) { $.getJSON(url3, function (data3) { //manipulate data1, data2, ...

how to pass arguments to module.exports in a Node.js application

I have created a code snippet to implement a Node.js REST API. app.js var connection = require('./database_connector'); connection.initalized(); // I need to pass the connection variable to the model var person_model = require('./mod ...

Interactive Jquery slider that moves based on mouse movement

Does anyone know of a jquery slider script that allows for horizontal sliding when moving the mouse? I am looking to achieve an effect similar to the one shown in this example, but specifically scrolling from right to left. ...

What causes a function loss when using the spread operator on window.localStorage?

I am attempting to enhance the window.localStorage object by adding custom methods and returning an object in the form of EnhancedStorageType, which includes extra members. Prior to using the spread operator, the storage.clear method is clearly defined... ...

Android experiencing issues with dynamically loading Border XML

I am having trouble setting a border dynamically for a RelativeLayout. Oddly enough, when I manually add the border in the activity XML file, it displays perfectly. However, when I try to generate the border dynamically, it doesn't appear. border.xml ...

Issue with Material-ui IconButton's edge properties not functioning as expected

Is there a way to position the delete icon on the right side of the screen? It seems like using edge= "end" is not working as expected. If you'd like to take a look, here is the sandbox link: https://codesandbox.io/s/admiring-silence-vwfoe? ...

Issue occurred in module.js:341 while attempting to include android platform to ionic using command line

For my hybrid app development using the Ionic framework, I made sure to install all required dependencies like node.js and cordova. Following their Getting started guide, I reached step 3 which instructs running this command within the app directory: > ...

Paging in Ext JS does not function properly when using local data sources

I am facing an issue with enabling paging in ExtJs4 grid. The paging toolbar appears to be functioning correctly, however, the paging feature does not seem to work within the grid itself. Can anyone provide guidance on what might be missing? Ext.onReady(f ...

Complete loading of iframe content on Internet Explorer versions 8 and 9

Having an issue with the full loading of a page in IE8-9. I need to perform certain actions after the content within a div is fully loaded, but it seems that in IE8-9, the page fails to load completely. This is causing problems as my actions are dependent ...

Issues arise with AJAX authentication request

Currently, I'm working on incorporating a basic login form with an AJAX request that forwards the user to a page for querying my database. Depending on the results, the user is then redirected to the main index page or prompted back to the login form. ...

When displaying a collection of components, clicking a button will always select the most recent element in the array

Can you explain why this code won't work in a React environment? Every time the button is clicked, it picks up the value "name" from the last element in the array. In this example, the dialog will always display the name "John2". import React from "r ...