Replacing text in JavaScript: Learn how to substitute a specific word in JavaScript using an array

I need assistance with updating the content of my div using PHP-like functionality. Is there a way to achieve this?

<?php
$val_1 = array('text_1', 'text_2');
$val_2 = array('text 1', 'text 2');
$replace = str_replace($val_1, $val_2, $div_id);
echo $div_id;
?>

The content within my div will initially be in English, but I would like to dynamically replace it based on the user's browser language.

For example, if the browser language is set to "fr," then the initial English text should be replaced accordingly, otherwise it remains in English.

<script>
var langs = "<?php echo substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2); ?>";
var myDiv = document.getElementById("msg_error");
var txt_1 = ["Hello world", "I love banana"];
var txt_2 = ["Bonjour le monde", "J'aime les bananes"];
   
    if(langs == "fr") {
        myDiv.innerHTML = txt_2[0]; // Update with French text
    } else {
        myDiv.innerHTML = txt_1[0]; // Keep original English text
    }
</script>

Your assistance in implementing this solution would be greatly appreciated!

Answer №1

function replaceStrings(a, b, c) {
    var copyText = c;
    if (typeof a === 'string' && typeof b === 'string') {
        copyText = copyText.replace(new RegExp(v, 'g'), b);
    } else if (Array.isArray(a)) {
        if (!Array.isArray(b)) {
            a.forEach((value) => {
                copyText = copyText.replace(new RegExp(value, 'g'), b);
            });
        } else {
            a.forEach((value, i) => {
                copyText = copyText.replace(new RegExp(value, 'g'), b[i]);
            });
        }
    }
    return copyText;
}

window.addEventListener('load', function() {
    var myContentDiv = document.getElementById('myContentDiv');
    var content = myContentDiv.innerText;
    var str1 = ["Hello world", "I love banana"];
    var str2 = ["Bonjour le monde", "J'aime les bananes"];
    myContentDiv.innerText = replaceStrings(str1, str2, content);
});
<div id="myContentDiv">Hello world, I love banana</div>

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

comparing multiple values separated by commas with JavaScript

I need validation using a comma-separated value format. Within the illustration, there are two fields: "Saloon Price" (value: 10,10,10,10) and "Saloon Offer Price" (value: 11,11,11,11). The first value must be less than the second. Saloon price Value & ...

Map Loader for GeoJson Leaflet Integration

Although my English skills are not perfect, I will do my best to explain my issue. I have some knowledge of javascript / html / ajax and I have created a webgis using Leaflet. The problem arises when loading a large geojson file onto the map - it takes qui ...

A guide to revealing the value of a button or anchor tag using AngularJS

I'm working on a way to show a button or anchor tag value depending on the true or false value returned by my angular variable. Here's a snippet of my code: <a href="#" id="verify">{{userInformation.value}}</a> The userInformation.v ...

Starting with NodeJS: Troubleshooting module not found error

I'm new to NodeJS and I'm following the guide on the official NodeJS site to create a server. I have successfully installed NodeJS on my computer and created an app.js file with the code below: const http = require('http'); const host ...

Viewing multiple pages and maintaining sessions in Laravel

I am currently working on a quiz application that involves multiple pages depending on the user's selection. However, I have encountered an issue with Laravel's pagination not saving previous page inputs. Is there a way to resolve this problem? A ...

Assign the value of "td" to the variable "val"

I am trying to set the value of my td element from my JavaScript JSON, but for some reason it doesn't seem to be working when I inspect the element. The HTML is functioning fine, it's just the value that isn't updating. I've tried chang ...

What strategies can be utilized to enhance the cleanliness of these functions?

Is there a way to avoid adding new lines of JS code every time I add a new image to the HTML? $(document).ready(function() { $('.btn').click(function() { var bid = $(this).attr('id'); if(bid=="img1" || bid == "img2" || bid == "img3"){ ...

Correct the spacing around periods, even within separate div elements

I am facing a challenge with a large json file resembling a decision tree, where each node contains a sentence. There are multiple buttons on the page, and each click on a button retrieves a node from the json to populate the HTML. The json structure: { ...

Is there a way to temporarily halt a jQuery animation for 2 seconds before automatically resuming it, without relying on mouse-over or mouse-out triggers?

With just one scrolling image implemented in jQuery, the logos of clients are displayed continuously in a scrolling box with no pauses. Speed can be adjusted easily, but pausing and then resuming the animation after 2 seconds seems to be a challenge whic ...

JavaScript functions with similar parent names

Explain a function that has identical functionality to its parent parent.document.getElementById(source).innerHTML should be the same as other-function-name.document.getElementById(source).innerHTML ...

Convert numbers to words in the Indian currency format as you type up to a 16-digit number, displaying the Indian rupees symbol automatically without the need to click a button

How can we modify the code below to automatically add the Indian rupees symbol in the input field? https://i.sstatic.net/TlNLc.png $('.allow_decimal').keyup(function (event) { $(this).val(function (index, value) { return valu ...

Eliminate HTML field based on checkbox status

I'm looking to dynamically remove HTML fields based on a Yes/No condition. I've shared the code below for better understanding. If Yes is selected, I want to hide the No Field/Input/Box and vice versa. function AutoCheck() { if (document.getEl ...

Exploring the capabilities of useRef in executing a function on a dynamically created element within a React/Remix/Prisma environment

I've been trying to implement multiple useRef and useEffect instructions, but I'm facing difficulties in getting them to work together in this scenario. The code structure involves: Remix/React, fetching data from a database, displaying the data ...

transferring a JavaScript variable to PHP upon submitting a form

This question arises after my previous inquiry on the topic of counting the rows in an HTML table using PHP. Since I didn't find a solution that worked for me, I am exploring new methods but struggling with the implementation. My approach involves ass ...

Tips on implementing a jQuery .load() function using an anchor tag within dynamic content

I am working on a search page where user input is taken from a form and then sent to a PHP file that makes a cURL call to an external server. The PHP file receives an array from the server, which it uses to display HTML in a "results" div on the original s ...

In an attempt to successfully retrieve data from a formatted XML API, I am working on making a straightforward API call using JavaScript/TypeScript

I'm currently working on a project that involves calling an API in XML format, but I'm having trouble getting any data to show up. So far, I've attempted to use both JavaScript and TypeScript for making the HTTP request, as well as trying o ...

Exploring the global document object within Next.js

We have been working on a project using nextjs and are facing an issue with changing the styling of a button upon click. Despite using document.getElementById, we are unable to change the styling no matter what we try. pages/index.js function Index() { ...

Example when a specific $scope.apply() is needed:

I am currently delving into the world of Angular and experimenting with different ways to learn how it functions. One of my projects involves creating a simple application where users can add new entries through an HTML interface, store them in a SQLite da ...

Using the Play framework to showcase data in an HTML table

I have a project where I am working with multiple tables, one of which is a Person table containing id and name attributes. I have successfully retrieved the data from the database using MySql and converted it into JSON. However, I am struggling to find a ...

Node.js: Breaking the Rules with an Illegal Break Statement

Struggling to generate a unique ID in Node.js and MongoDB, using a while loop that checks existing IDs in MongoDB until a unique value is found. If the ID is already taken, a number is added to the end until Mongo returns no results. Everything seems to b ...