Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7947749
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 4, 20262026-06-04T01:31:19+00:00 2026-06-04T01:31:19+00:00

I am using jQuery and I need to create a Find / Replace form

  • 0

I am using jQuery and I need to create a Find / Replace form for text that is pulled from a text file “example.txt”.

First, here is the HTML:

<div id="outbox" class="outbox">
<h3>Output</h3>
<div id="output"></div>
</div>
<div class="content">
<h3>Text File Location</h3>
<br />
<form id="prac" action="prac9.html">
    <input id="locator" type="text" value="example.txt" /> <br />
    <input id="btnlocate" value="Load" type="button" />
</form>
<br />
<h3>String Search</h3>
<form id="prac2" action="prac9.html">
    <div id='input'><input type='text' id='fancy-input'/> ...Start Typing</div> <br />

</form>
<br />
<h3>Find / Replace String</h3>
<form id="prac3" action="prac9.html">
    <input id="findtxt" type="text" value="" /> Find <br />
    <input id="replacetxt" type="text" value="" /> Replace<br />
    <input id="btnreplace" value="Find & Replace" type="button" />
</form>
</div>

Here is the jQuery/JS:

<script type="text/javascript">

$('#btnlocate').click(function () {

    $.get($('#locator').val(), function (data) {
        var lines = data.split("\n");
        $.each(lines, function (n, elem) {
            $('#output').append('<div>' + elem + '</div>');
            // text loaded and printed
        });
    });
});

/* SEARCH FUNCTION */

$(function () {       

    $('#fancy-input').keyup(function () {
        var regex;
        $('#output').highlightRegex();
        try { regex = new RegExp($(this).val(), 'ig') }
        catch (e) { $('#fancy-input').addClass('error') }

        if (typeof regex !== 'undefined') {
            $(this).removeClass('error');
            if ($(this).val() != '')
                $('#output').highlightRegex(regex);
        }
    })
});

 /* SEARCH FUNCTION FOR FIND REPLACE */
 $(function () {
    $('#findtxt').keyup(function () {
        var regex;
        $('#output').highlightRegex();
        try { regex = new RegExp($(this).val(), 'ig') }
        catch (e) { $('#findtxt').addClass('error') }

        if (typeof regex !== 'undefined') {
            $(this).removeClass('error');
            if ($(this).val() != '')
                $('#output').highlightRegex(regex);
        }
        })
    });

 /* regexp escaping function */

  RegExp.escape = function (str) {
      return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
  };

    $('#btnreplace').click(function () {
        var needle = $('#findtxt').val();
        var newneedle = $('#replacetxt').val();
        var haystack = $('#output').text();
      //  var regex = new RegExp(needle, "g");
        haystack = haystack.replace(new RegExp(RegExp.escape(needle), "g"), newneedle);
        console.log(haystack);
    });

As you may have noticed, I have used a plugin “jQuery Highlight Regex Plugin v0.1.1” if that’s relevant.

http://pastebin.com/HmqWmKsy is “example.txt” if that’s relevant also.

All I need is a simple way of doing this find / replace but all the stuff on the web has yet to help me.

If you need anymore info, let me know please.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-04T01:31:21+00:00Added an answer on June 4, 2026 at 1:31 am

    You’re on the right track using replace and a regular expression. You want to add the “global” flag (g), and you’ll have to create the expression via new RegExp(string) because your needle is a string. E.g.:

    haystack = haystack.replace(new RegExp(needle, "g"), newNeedle); // BUT SEE BELOW
    

    The above almost works, except that if there are any characters in needle that are special in regular expressions (*, [], and the like), obviously new RegExp will try to interpret them. Unfortunately, RegExp doesn’t have a standard means of escaping all of the regex characters in a string, but you can add it:

    RegExp.escape = function(str) {
      return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
    };
    

    (That’s from Prototype, but we can just copy it rather than actually using the entire library, it’s MIT-licensed. Be sure to attribute in your source. Or alternately use this version from elsewhere.)

    So we end up with:

    haystack = haystack.replace(new RegExp(RegExp.escape(needle), "g"), newNeedle);
    

    Here’s a full working example: Live copy | source

    HTML:

    <div>
      <label>Haystack:
        <br><textarea id="theHaystack" rows="5" cols="50">Haystack with test*value more than once test*value</textarea>
      </label>
    </div>
    <div>
      <label>Needle:
        <br><input type="text" id="theNeedle" value="test*value">
      </label>
    </div>
    <div>
      <label>New Needle:
        <br><input type="text" id="theNewNeedle" value="NEW TEXT">
      </label>
    </div>
    <div>
      <label>New haystack:
        <br><textarea readonly id="theNewHaystack" rows="5" cols="50"></textarea>
      </label>
    </div>
    <div>
      <button id="theButton">Replace</button>
    </div>
    

    JavaScript:

    RegExp.escape = function(str) {
      return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
    };
    jQuery(function($) {
    
      $("#theButton").click(function() {
        var haystack = $("#theHaystack").val(),
            needle   = $("#theNeedle").val(),
            newNeedle = $("#theNewNeedle").val(),
            newHaystack;
    
        if (!haystack || !needle) {
          display("Please fill in both haystack and needle");
          return;
        }
    
        newHaystack = haystack.replace(
          new RegExp(RegExp.escape(needle), "g"),
          newNeedle);
        $("#theNewHaystack").val(newHaystack);
      });
    
      function display(msg) {
        $("<p>").html(msg).appendTo(document.body);
      }
    });
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I need to create a web application using ASP.NET MVC, jQuery and web standards
using jquery I need to retrieve an array from table cells, format the data
i need to trim a string to its first 100 characters using jquery/javascript. also
I need to write, in JavaScript (I am using jQuery), a function that is
I'm trying to create a simple file upload form for my website. I'm using
I am using jquery UI range slider in my site, I need to create
Hi I need to parse XML file using jquery. I created read and display
I'm using mostly jQuery (with asp.net), however I need to create a questionnaire. The
I am using jQuery UI to create 2 tabs. I really only need the
I am trying to create a form that utilizes PHP and Jquery AJAX form

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.