Using JavaScript, swap out the text enclosed in square brackets with an array

Changing the text inside square brackets with values from an array is my goal.

For instance:

<pre id="text">
[maybe] i should [leave]
[to] help you [see]
[nothing] is [better] [than] this
[and] this is [everything] we need
</pre>

The transformed version will look like this:

<pre id="text">
[why] i should [go]
[from] help you [run]
[that] is [nothing] [from] this
[now] this is [as] we need
</pre>

I would appreciate your assistance. Thank you

var arr = ['why', 'go', 'from', 'run', 'that', 'nothing', 'from', 'now', 'as']
var i = 0;
$("#text").each(function() {
  $(this).text($(this).text().replace(/\[(.+?)\]/, "["+arr[i]+"]"));
i++;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre id="text">
[maybe] i should [leave]
[to] help you [see]
[nothing] is [better] [than] this
[and] this is [everything] we need
</pre>

Answer №1

.each() isn't executed for each line within a tag; rather, it is triggered for every element with a specific class or for each element with a certain tag name. To learn more about .each(), check out the documentation here.

Take a look at this code snippet:

$(document).ready(function() {
  var arr = ['why', 'go', 'from', 'run', 'that', 'nothing', 'from', 'now', 'as']
  var text = $("#text").text();
  var count = -1;
  $("#text").text(text.replace(/\[(.*?)\]/g, function() {
    count = count + 1;
    return "["+arr[count]+"]"
  }));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre id="text">
[maybe] i should [leave]
[to] help you [see]
[nothing] is [better] [than] this
[and] this is [everything] we need
</pre>

Answer №2

Using an object with words for replacement instead of an array can be a more organized approach. When a word is detected, the corresponding value from the object can be used for substitution.

var words = { maybe: 'why', leave: 'go', to: 'from', see: 'run', nothing: 'that', better: 'nothing', than: 'from', and: 'now', everything: 'as' },
    text = document.getElementById('text');

text.innerHTML = text.innerHTML.replace(/\[([^\]\[]+)\]/g, function (_, k) {
    return '[' + words[k] + ']';
});
<pre id="text">
[maybe] i should [leave]
[to] help you [see]
[nothing] is [better] [than] this
[and] this is [everything] we need
</pre>

This method relies on the order of the items for replacement, ensuring they are replaced in the same sequence.

function replacer (array) {
    var i = 0;
    return function () {
        return '[' + array[i++] + ']';
    };
}

var words = ['why', 'go', 'from', 'run', 'that', 'nothing', 'from', 'now', 'as'],
    text = document.getElementById('text');

text.innerHTML = text.innerHTML.replace(/\[([^\]\[]+)\]/g, replacer(words));
<pre id="text">
[maybe] i should [leave]
[to] help you [see]
[nothing] is [better] [than] this
[and] this is [everything] we need
</pre>

Answer №3

function swap_terms(replace_array, sentence){
   let index = 0;
   return sentence.replace( /\[(\w+)\]/g, word => `[${replace_array[index++] || word}]` );
}
const sentence = "[perhaps] i might [depart] [to] assist you [perceive] [nothing] is [superior] [than] this [and] this is [all] we require"
const array_replace = ['because', 'leave', 'from', 'run', 'that', 'nothing', 'better', 'now', 'as'];
console.log( swap_terms( array_replace, sentence ) )

Answer №4

To update the content, utilize the String.prototype.replace() method along with a callback for replacement:

var text = document.getElementById("text"),
    arr = ['why', 'go', 'from', 'run', 'that', 'nothing', 'from', 'now', 'as'],
    count = 0;

text.innerHTML = text.innerHTML.replace(/\[([^\]\[]+)\]/g, function (match, group) {
    return '[' + arr[count++] + ']';
});
<pre id="text">
[maybe] i should [leave]
[to] help you [see]
[nothing] is [better] [than] this
[and] this is [everything] we need
</pre>

Answer №5

Attempting a solution:

$(document).ready(function(){
        arr.forEach(function(element){  
        $("#text").text($("#text").text().replace(/\[.+?\]/, element ));
        });
});

The code successfully produces the desired output without brackets; however, when adding brackets like this:

.replace(/\[.+?\]/, "[" + element + "]"));
, it stops working. (Any suggestions on how to modify this are welcome)

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

Styling a table based on specific conditions using Angular and JavaScript

I am trying to conditionally style the text in the table based on the time elapsed since the last ping. Specifically, I want to change the color of the text from green to red once 5 minutes have passed and vice versa. <form name="myform" data-ng-submit ...

The WebSocket function is returning undefined even though it successfully fetches the user; however, the user is

I've been experimenting with a websocket to retrieve user information. When I establish the connection and send messages to receive the data, it returns undefined when I try to use that information elsewhere. However, if I run console.log within the ...

Vanishing Tooltip following an implementation of the backdrop-filter

I'm having an issue with the blur effect on my background image. Although it works well, my tooltips also end up being blurred behind the divs: https://i.stack.imgur.com/BMdh4.png Is there a way to ensure that my tooltips stay on top of the subseque ...

What is causing the return statement to not function properly in the Mongoose findOne method?

I am attempting to locate an item by its name, then update the table and return the updated result. However, the return statement is not working as expected in my code: class addSongsToArtist { constructor(artistName) { Artist.findOne({ ...

Automatically calculate the multiplication of a number by 10 in React JS within the State

In this scenario, I am looking for assistance in creating a functionality where the user can adjust numbers in an input box and see the result of that number multiplied by 10 in a nearby span element. However, I am encountering issues with fetching the des ...

Sending data using the AJAX method with integers

Utilizing AJAX to send a high score to a SQLite database's highScores table, the total of the high score must be calculated through a query and then retrieved back from the database. How can I ensure that the score is sent as an integer through AJAX t ...

The unexpected postbacks caused by the ASP.NET MVC DropDownList appear to stem from JavaScript, catching me by surprise

In my MVC project, there's a standard form with a dropdown list. Each time I change the dropdown value, the entire page reloads due to a postback. This behavior is unexpected, and I want to prevent the dropdown from triggering a postback. Strangely, ...

"Enhance your Django website with a dynamic voting button using AJAX

I am working on a project where I have implemented the following code: (r'^oyla/(\d+)/$', oyla), Here is the view associated with this code snippet: @login_required def oyla(request, id): if request.is_ajax(): entry = Entry.ob ...

Implementing nested popup windows using Bootstrap

I am facing an issue with my two-page sign-in and sign-up setup in the header of my angular2 project. On the sign-up page, I have a link that should redirect to the sign-in page when clicked, but I am struggling to make it work. Can someone provide guidanc ...

Showcasing Portfolio Work in a User-Friendly Mobile Design

Currently revamping my portfolio website and looking for ways to optimize the display of my personal projects. I have a card-like interface in place that works well on desktop but only shows one project at a time on mobile devices. Seeking solutions to imp ...

Unexpected event in Coffeescript and Express framework: a tangled web of mysteries

Currently, I am working on developing an app using Express.js and Coffeescript. My code can be found here: https://github.com/findjashua/contactlist However, upon trying to run the application, I encounter the following error: app.coffee:11:24: error: un ...

Obtain an array containing only unique values from a combination of arrays

Is there a simple way or plugin that can help me combine values from multiple arrays into one new array without duplicates? var x = { "12": [3, 4], "13": [3], "14": [1, 4] }; The resulting array should only contain unique values: [1, 3, 4]; ...

What could be the root cause behind this Selenium mistake?

My goal is to verify the correct scroll position in the browser using NightwatchJS and Selenium. Below is the command I am using in Nightwatch: assertScrollPosition(testValue) { this.api.execute(() => { const offsetValue = w ...

Is there a way to get an iframe to mimic the behavior of other media elements within a horizontal scrolling container?

Take a look at this code snippet: $(document).ready(function() { $('.scrollable-area').on('wheel', function(e) { var scrollLeft = $(this).scrollLeft(); var width = $(this).get(0).scrollWidth - $(this).width(); var delta ...

What is the best way to update or reload an embedded application/pdf?

I have implemented an embed code using application/pdf in order to display a pdf document on the website. To dynamically change the src attribute of the embed when a link is clicked, I utilized javascript. I confirmed this action by displaying alerts to e ...

Error occurs when React-router 6 cannot render an error component

I'm facing an issue in my React app where the custom error component I created for unmatched routes is not being rendered, instead the default error page appears. Here's a snippet of how my BrowserRouter is set up: const router = createBrowserRo ...

ModSecurity Action Causing AJAX Problem

An error is being triggered by the URL below with a message of "Modsecurity forbidden status code: 403". This URL is being returned from an AJAX call. like ? and active = ?&params='%ABCDE%'|1&element_id=hello If I remove %% from ABCDE ...

What are the best practices for managing data input effectively?

I am facing a challenge with input validation. I need to restrict the input to only accept strings of numbers ([0-9]) for the entity input field. If anything else is entered, I want to prevent it from overwriting the value and displaying incorrect input. I ...

AJAX allows developers to declare variables within their code to

Here is a snippet of my JavaScript code: $(\"img.agree\").click(function() { var follow_id = $(this).attr(\"id\"); var user_id = $(\"img.user_id\").attr(\"id\"); $.ajax({ type: \"POST& ...

I am encountering an issue with the Node library puppeteer when trying to integrate it with vue.js

While following a YouTube tutorial on utilizing puppeteer in JavaScript, I encountered an issue where the page would not render even if I required the library. The problem seemed to be located right below where I imported my Vue components: <script> ...