Tips for substituting a pair of terms with equivalent ones from an array using Arabic JavaScript

In my array, I have the months written in English and the days of the week also in English.

I am trying to replace the English words with their Arabic equivalents at the corresponding index in the array. My code looks simple and clean, but for some reason, it is not working. I have tried using two replace functions.

// English
var en_months = ['January','February','March','April','May','June','July','August','September','October','November','December'];
var en_days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']

// Arabic
var ar_months = ['كانون الثاني','شباط','آذار','نيسان','أيار','حزيران','تموز','آب','أيلول','تشرين الأول','تشرين الثاني','كانون الأول'];
var ar_days = ['الأحَد','الإثْنَين','الثَلاثاء','الأربَعاء','الخَميس','الجُمُعة','السَبْت']


// ACTION
jQuery("span.date").text(function(i, val) {
    return val.replace(en_months, ar_months);
    return val.replace(en_days, ar_days);
});

This is an example of the span:

<span class="date">Wednesday, October 7th, 2015</span>
There are multiple instances of this on the page.

Answer №1

When it comes to replacing elements, you can utilize the power of RegExp. In the RegExp object, you can define a pattern as a string, as demonstrated in my example. I converted the en_months array to a string using the .join method. Additionally, the indexOf method is used to find the first index of a specified element. For instance, if "October" exists in the array, it will return 9. By using this index, the corresponding element is retrieved from either ar_months or ar_days, which is then replaced using the .replace method.

// English
var en_months = ['January','February','March','April','May','June','July','August','September','October','November','December'];

var en_days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']

// Arabic
var ar_months = ['كانون الثاني','شباط','آذار','نيسان','أيار','حزيران','تموز','آب','أيلول','تشرين الأول','تشرين الثاني','كانون الأول'];
var ar_days = ['الأحَد','الإثْنَين','الثَلاثاء','الأربَعاء','الخَميس','الجُمُعة','السَبْت']

// GO FOR IT
$("span.date").text(function(i, val) {
    val = val.replace(new RegExp(en_months.join('|')), function (match) {
        return ar_months[en_months.indexOf(match)] || match;
    });
    
    val = val.replace(new RegExp(en_days.join('|')), function (match) {
        return ar_days[en_days.indexOf(match)] || match;
    });
    
    return val;
});
.date {
   direction: rtl;
   display: inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="date">Wednesday, October 7th, 2015</span>

Answer №2

To update the values, you must iterate through each possible value and replace them individually.
The function stops executing after encountering the first return ....

jQuery("span.date").text(function() {
    var text = val,
        i;

    for (i = 0; i < en_months.length; i++) {
        text = text.replace(en_months[i], ar_months[i]);
    }
    for (i = 0; i < en_days.length; i++) {
        text = text.replace(en_days[i], ar_days[i]);
    }

    return text;
});

Check out the fiddle

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

Ensuring the value of a v-text-field in Vuetify using Cypress

I am currently developing an end-to-end test suite using Cypress for my Vue and Vuetify frontend framework. My goal is to evaluate the value of a read-only v-text-field, which displays a computed property based on user input. The implementation of my v-tex ...

How to Overcome Read-only HTML Components in Selenium with Python?

I am working on automating a task using Selenium in Python, and part of it involves selecting a date. The website I am testing has an input box for date selection that displays a standard date table when clicked. Unfortunately, the input text box is read- ...

AJAX enhancing the functionality of the webgrid with dynamic filtering

I'm encountering a problem with implementing JS on my webgrid for sorting purposes. The scenario is that a user enters a string into a textbox and the webgrid below is refreshed (filtered based on matching results) without the entire page being refres ...

Is there a way to include this function in an array without triggering it right away?

In my coding project, I am working with an array of functions that return jQuery deferred AJAX objects known as phoneAjaxCalls. The main function called newPhone is where multiple calls are being pushed and it requires two arguments. function newPhone(tlc ...

Printing feature not functioning properly on Internet Explorer version 11

Currently, I am facing an issue with printing a document using a blob URL and iFrame. Everything works perfectly in Chrome, but unfortunately, it's not functioning properly in IE browser. I need guidance on how to successfully print a blob URL that i ...

Ways to emphasize the contrast between two texts using CSS

One method to highlight specific parts of text using CSS can be found in this script: span.highlight { background-color: #B4D5FF; } However, what if we want to highlight the differences between two strings? Take for example these two strings: this ...

Generating CSV headers for all nested objects in JavaScript

Utilizing the "react-json-to-csv" library to convert my JSON data into a CSV file has presented an issue with nested objects. The CSV export header is breaking, displaying alternate data because of these nested objects. Here's an example of my JSON da ...

Locate the closest larger value for each element within the array

Could someone help me find a speedy algorithm to solve the following problem? To put it formally, given an array element ai, I need to determine the index j where j > i ai < aj the difference j - i is as small as possible Below is a demonstration ...

The NextJs image entered into an endless loop, throwing an error message that said: "The 'url' parameter is correct, but the response from the

I have been using next/image component with next js version ^12.2.3-canary.17 for my current project. The issue I am encountering is that some images are missing from the source directory, resulting in infinite error logs like the one shown below: https:/ ...

The Google map shifts beyond the perceived limits of the world

Is anyone else encountering an issue with Google Maps where you can now pan beyond the poles? It used to stop at the poles before, correct? The website I'm currently working on runs a location-based query on our server every time a user pans or zooms ...

Determining the quantity of regions with valid data in a two-dimensional array

Can someone help me with a question I have about my homework? I'm scratching my head over it. I need to create a program that counts the number of true value areas (near to each other) in a 2D array. {0,1,0,0} {1,0,0,1} {1,1,0,1} {1,0,0,1} The progra ...

Public directory assets not accessible

After working extensively with Node and Angular, I realized my back-end structure needed some serious attention. In an effort to streamline my process, I decided to separate the client and server components and create a reusable skeleton for future applica ...

Leveraging Redux and React to efficiently map state to props, while efficiently managing large volumes of data and efficiently

Utilizing sockets for server listening, the Redux store undergoes continuous updates with a vast amount of data. While updating the store is quick, the process of connecting the state to the component through the redux connect function seems to be slower, ...

Struggling to save a signature created with an HTML5 Canvas to the database

I've been on the hunt for a reliable signature capture script that can save signatures to MySQL, and I finally found one that fits the bill. However, there are two issues that need addressing: The canvas doesn't clear the signature when the c ...

Reading data from Firestore in Next.js

I came across a Next.js starter that retrieves data from Firestore v9, but it only displays the data after a click event. How can I modify this code in Next.js to automatically show the data without needing to click? import { db } from '@/lib/firebase ...

Modify the value of a CSS property through JavaScript

Hey there, I'm wondering how to change a CSS value of the document itself, rather than targeting a specific element. I've already looked into solutions like Change :hover CSS properties with JavaScript, but they all involve adding CSS rules. I a ...

Vue: Issue with Firebase Authentication REST API triggers 400 Bad Request Error

Here is the error message I am encountering: POST scheme https host identitytoolkit.googleapis.com filename /v1/accounts:signUp key AIzaSyAk1ueCLjDDWCNrt_23o5A4RCfeaYIlN6k Address 74.125.24.95:443 Status 400 Bad Request VersionHTTP/3 Transferred850 B ...

Access an array element based on its value

Apologies for the odd phrasing, but I'm unsure of the correct terminology for this. I currently have an array that looks like this: [#<Item:0x007faeea066508 @name="Backpack", @exam="Not much here... just a backpack">] Essentially, this array r ...

"An issue with ng-controller in AngularJS causing a simple error

Currently, I'm in the process of learning angularJS. While ng-app and ng-model are functioning properly, I've encountered an issue with ng-controller. Despite my efforts, I can't seem to pinpoint where I've gone wrong. My code isn' ...

What is the process for incorporating ejs into the source attribute of an image element?

Code Snippet: <img class="card-img-top" alt="..."><%= articles.image %><img> Server Setup: const express = require('express') const app = express() const router = require('./routes/article') app ...