Replacing words as the user is inputting text (JavaScript)

I'm currently working on a code that displays what a user is typing and then echoes that input into an HTML document. Here's the code snippet:

<html><head>
<script src="http://code.jquery.com/jquery-1.9.0.min.js"></script>
<script src="jquery.zclip.js"></script>
<style> body{font-family:century gothic;}</style>
</head>
<body style="zoom: 1;">

<div style="padding:10%;">

<textarea type="text" name="fname" class="chatinput" style="margin: 0px; width:   977px; height: 324px;"> </textarea>
<div style="padding-top:10%;" class="printchatbox"></div>


<script type="text/javascript" src="jquery-1.8.0.min.js"></script> 
<script src="jquery.zclip.js"></script>

<script type="text/javascript">
$('.chatinput').keyup(function(event) {
newText = event.target.value;
$('.printchatbox').text(newText);
});  
</script>

I need help in figuring out how to dynamically replace a word or phrase with something else while the user is typing. For example, if the user types "this is a string," I want the program to automatically change it to "This is a text" as it appears in the HTML document. Any assistance would be greatly appreciated!

Answer №1

To view the demonstration on my fiddle, click here.

I have crafted an object in which you can input all strings that require replacing along with their respective replacements in a key-value format. It is important to remember to escape special characters for RegExp by using a \.

JavaScript

var replaceValues = {
    'string' : 'text',
    'foo' : 'bar'
}

$('.chatinput').keyup(function (event) {
    newText = event.target.value;
    for (var txt in replaceValues) {
        var temp = new RegExp(txt, 'gim');
        newText = newText.replace(temp, replaceValues[txt]);
    }
    $('.printchatbox').text(newText);
});

Answer №2

If you want to modify the content of a variable, you can do so by using the replace function.

<html><head>
<script src="http://code.jquery.com/jquery-1.9.0.min.js"></script>
<script src="jquery.zclip.js"></script>
<style> body{font-family:century gothic;}</style>
</head>
<body style="zoom: 1;">

<div style="padding:10%;">


<textarea type="text" name="fname" class="chatinput" style="margin: 0px; width:   977px; height: 324px;"> </textarea>
<div style="padding-top:10%;" class="printchatbox"></div>




<script type="text/javascript" src="jquery-1.8.0.min.js"></script> 
<script src="jquery.zclip.js"></script>



<script type="text/javascript">
$('.chatinput').keyup(function(event) {
newText = event.target.value;
$('.printchatbox').text(newText.replace("This is a string","This is a text"));
});  
</script>

Answer №3

 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<textarea type="text" name="fname" class="chatinput" style="margin: 0px; width:   977px; height: 324px;"> </textarea>
<div style="padding-top:10%;" class="printchatbox"></div>

<script type="text/javascript">
$('.chatinput').keyup(function() {
var newText = $('.chatinput').val();
$('.printchatbox').text(newText);
});  
</script>

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

Ways to retrieve parameters in the following function using Express

I need help accessing fromFlight and toFlight variables in the next function that I have defined. Currently, I am only getting the output of the entire req object. Can someone assist me with this issue? Below is a snippet of my code: const express = requ ...

What is the best way to automatically focus on the initial input field in a form after clicking the submit button?

Check out this HTML form: <form> <input type="text" id="input1"> <input type="text"> <button>Submit</button> </form> When clicked, I want the focus to move to #input1 from the S ...

Leveraging Amplify for offline storage while transitioning between HTTP and HTTPS protocols

Recently, I encountered an issue with Amplify 1.0a1 on my website. It seems that when storing the value of prod_id in localStorage on a page using HTTP, and then navigating to a page using HTTPS (such as the 'list' page), I am unable to access th ...

PHP array index malfunction

I've been banging my head against the wall for hours trying to figure out what I'm doing wrong here. It just doesn't add up. <?php date_default_timezone_set('America/New_York'); $json = file_get_contents('https://www ...

Automatically bypassing git conflicts in package.json: A step-by-step guide

We encounter frequent updates to shared npm packages in our app, resulting in multiple pull requests updating the same package version. Consequently, conflicts arise on GitHub when these pulls are merged into the master branch. Is there a way to automati ...

Ensuring that all popovers are horizontally aligned across the entire page

My Bootstrap form comes with several input fields, some of which are in multicolumn rows, and I would like them to display a popover upon focus. While the standard implementation allows me to show a popover next to the input field, my preference is to hav ...

How can an array of file paths be transformed into a tree structure?

I am looking to transform a list of file and folder paths into a tree object structure (an array of objects where the children points to the array itself): type TreeItem<T> = { title: T key: T type: 'tree' | 'blob' childr ...

Error occurred in imagemin: [TypeError: (input, output, options) => {

function optimizeImages(originalFilePath, destinationFilePath) { return new Promise(function (resolve, reject){ var Imagemin = require('imagemin'); console.log(originalFilePath); // /app/public/images/temporary/4du_QIGCJb5.jpeg con ...

Eliminate the use of 'sip:' when dialing the number

I am currently using the softphone eyebeam to make calls. Whenever I click on a SIP link like this: <a href="sip:0123456789">0123456789</a> The issue arises when eyeBeam adds the "sip:" prefix before the number, causing it not to recogniz ...

Unlocking the secrets of capturing key presses before submitting with jQuery

I'm seeking help with creating an app that scans a barcode and displays the data on screen. I prefer not to use textboxes in order to prevent data editing. Currently, I have set up the enter key to be automatically sent at the end of the barcode scan ...

Buttons that are set to float will not be positioned below an inline edit popup

In my setup, there is a table with an inline edit popup in the tbody section that is absolutely positioned. Within the table footer, there is a display of inline-block that holds buttons floated to the left and right, as shown below: <div class="table ...

Is there a method to ascertain the relative position of a point on a polygon?

Apologies in advance as I might have a hard time wording this question properly, so I'll start by explaining my objective. I'm currently working with JavaScript and Raphael. My goal is to save the position of a point in relation to the four cor ...

Tips for converting text from an HTML input field to a JSON file

After designing a form with four text fields and a submit button, my goal is to save the data into a JSON file upon submission. Additionally, I am looking for a way to display all of the JSON data on my webpage. ...

Checking for the existence of a value in an object using Angular loops

I am seeking assistance in verifying the presence of a specific value within an object. My Object = (vagas.etapas) "Etapas" : { "05daf060-87cb-47cf-8c98-65b36941613d" : "Name 1", "0bf7aabf-42df-4f7d-86dc-af81e6cef394 ...

Access cookie information within a Vue application by reading it within the router or component

There is a url (*/webapp/callback) in my vue.js app that gets redirected (http 302) from another application, bringing along some cookies. I'm trying to figure out how I can read these cookies when the component mounts and then store them in vuex stat ...

Steps for adjusting an image in a Bootstrap Carousel

Currently tackling a simple bootstrap Carousel for a school project. I've adjusted the max-height of the images to 400px but it seems like only the top part of the images is visible. I attempted to adjust the margins on the image, and even thought abo ...

How can I find values in a multidimensional PHP array based on a specific value and retrieve other associated

I have come across this array example: Array ( [0] => Array ( [cast_id] => 45 [character] => Evelyn Salt [credit_id] => 52fe4555c3a368484e054141 [gender] => 1 [id] => 11701 [name] => Angelina Jolie [order] => 0 [profile_path] => ...

Step-by-step guide on populating a state using an array

I am having trouble populating a list within a state using the set method, as the state remains empty App.js // Initiates the secrets word game const startGame = () => { // pick word and pick category const { word, category } = pickWordAndCat ...

Having trouble getting the HTML5 Video to play using the AngularJS ng-src tag?

There seems to be an issue with AngularJS ng-src not working properly with the HTML5 Video element in this specific fiddle: http://jsfiddle.net/FsHah/5/ Upon inspecting the video element, it appears that the src tag is correctly filled with the appropriat ...

Looking for a regex solution in C# to eliminate and substitute specific HTML tags based on two conditions - it is needed

1) CHANGE only a few HTML tags with their corresponding HTML tag equivalents. Example: Replace h1 tag with h4 tags and replace div tag with p tag. Input: <div><h1>First</h1><h1 align='center'>Second</h1></div& ...