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

Challenges encountered when using random values in Tailwind CSS with React

Having trouble creating a react component that changes the width based on a parameter. I can't figure out why it's not working. function Bar() { const p =80 const style = `bg-slate-500 h-8 w-[${p.toFixed(1)}%]` console.log(styl ...

Encountering a TypeError in Next.js: "Unable to redefine property: $$id" -

Currently, I am immersed in a Next.js tutorial while following a YouTube guide. The project involves creating a mimic of Facebook Threads to enhance my understanding of Next.js. However, when attempting to create a thread (or a simple post), the applicatio ...

Notify when a variable matches the value of a div

I am attempting to display an alert message when my JavaScript var is equal to the value of a div. Here is the code I'm using: function checkMyDiv() { var elementCssClass = document.getElementById("Target"); if (elementCssClass == "hello") ...

One interesting characteristic of Javascript localStorage is that it overrides existing data instead of adding to it

I've been experimenting with localStorage to create new divs dynamically. Everything is going well, but I encountered an issue after reloading the page and clicking the bag button again. The previously created divs are being replaced by the new ones i ...

A new version of Primefaces has been released, introducing a sleek button feature with

How can I utilize the Primefaces version 10 button with a Font Awesome icon, resizing the icon without displaying the words ui:button? A and B are tests that I can resize successfully, but they are not buttons. C and D are buttons where the icon is resize ...

How can I use jQuery to show an HTML dropdown menu populated from PHP?

Currently, I am working with a PHP backend that retrieves data from SQL. Specifically, it pulls a list of user ID numbers. I would like to showcase that list within an HTML select element using jQuery after a button is clicked. While contemplating how to ...

What's the process for including delivery charges in Stripe transactions?

I am facing an issue with Stripe where I am unable to incorporate delivery fees into my transactions. How can I successfully integrate this feature? let line_items = []; for (let productId of uniqIds) { const quantity = productsIds.filter(id => id == ...

Issues with the modal in Angular not closing ($uibModal)

angular .module('angProj') .controller('UserCtrl', ['$scope', '$uibModal', function ($scope, $uibModal) { $scope.results = function (content, completed) { var modalInstance = ...

Arranging a list of objects with a designated starting value to remain at the forefront

Consider the array and variable shown below: array = ['complete','in_progress','planned']; value = 'planned'; The goal is to always sort the array starting with the 'value' variable, resulting in: array ...

Is it possible to detect inline elements that have been wrapped?

I am facing a challenge with displaying an indefinite amount of in-line elements. Depending on the width of the browser, some elements may shift to a new line. I am curious to know if it is possible to identify and isolate these rows of elements, or if the ...

Prevent complete deletion of table while there are still rows present

This section of code serves a dual purpose: It checks the dates in each row of a table and deletes any rows where the date is in the past. If all the rows in a table have past dates, it removes the entire table. The second function, however, is not func ...

javascript - Retrieving a JSON string

I am currently working on a stock website where I need to retrieve JSON information from either Google's API or Yahoo's API. To test this functionality, I have used a replacement function to log the data onto a text box for testing purposes. Howe ...

Creating a Authentic Screw Top Appearance with CSS

I am striving to create a realistic screw head. Here is what I have done so far: <div class="screw"><div class="indent"></div></div> .screw { position: absolute; top: 10px; left: 49%; width: 30px; height: 30px ...

Checkmate with React Native's Checkbox Component

I have implemented the React Native Elements CheckBox inside List Items within a Flat List. import React, { Component } from "react"; import { View, Text, StyleSheet, FlatList } from "react-native"; import axios from 'axios&apo ...

Error: The JSON data contains an unexpected token at the beginning Express

I am currently following a tutorial (here) to establish a connection between Express and React Native. I have a server.js script running which connects to the client (App.tsx) on my IP address using port 3000. The server and app are running simultaneously ...

Assistance with changing styles

Hey there, I could really use some assistance. I've created a style switcher, but I'm struggling to figure out how to replace the stylesheet properly. Currently, my code empties the <head> element when what I really need is for it to simply ...

Node API is failing to insert user data into MongoDB

I'm currently developing a Restful API using Node.js and storing data in Mongodb, focusing on the user registration API. app.js apiRoutes.post('/signup', function(req, res) { if (!req.body.name || !req.body.password) { res.json({suc ...

React: Struggling to render values within {} of a multidimensional object

I'm facing a challenge that I can't seem to overcome and haven't found a solution for. The values between curly braces are not displaying in the Content and Total components. I've double-checked the JSX rules, but it seems like I might ...

Converting SHA-256 from Java to JavaScript in an Ionic project using NPM: A step-by-step guide

In Java, I have a code snippet that needs to be converted into JavaScript using the Ionic Framework. I attempted to use Ionic App along with NPM packages like "crypto-js" and "js-sha256", but I was unable to find a suitable solution. String generate ...

Whenever I try to make my links responsive, they don't seem to work as intended

This is the HTML snippet <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> ...