Enhance the efficiency of the replace function in JavaScript

Seeking a more efficient approach to perform this function, could you provide some assistance?

  function removeAccents(text) {

        var text = text.replace(/á/g, "a").replace(/é/g, "e").replace(/í/g, "i").replace(/ó/g, "o").replace(/ú/g, "u");

        return cadenaTexto;

    }

Answer №1

Your code seems clean already, perhaps putting the replaces on separate lines could enhance readability, but overall it's easy to comprehend.

I've taken a different approach with the code below, leveraging the ability to use a replacerFunction in String.prototype.replace

This method allows you to define which characters you want to replace along with their replacements in a separate object and simply pass them into the function.

function removeAccents(text) {
  const translations = { á: "a", é: "e", í: "i", ó: "o", ú: "u" };
  return text.replace(/[áéíóú]/g, match => translations[match]);
}

console.log(removeAccents("áéíóú"));

Answer №2

UPDATE: After testing various solutions, @Ryan White's method using the match callback proved to be the most efficient. It showed a significant improvement in performance ranging from 20% for shorter strings to over 100% for longer ones. This approach outperformed the alternatives below as it eliminates the need for loops:

const replacements = { à: 'a', è: 'e', ì: 'i', ò: 'o', ù: 'u' };

function removeAccents3(text) {
  const accs = Object.keys(replacements).join('')
  return text.replace(
    new RegExp(`[${accs}]`, 'gi'),
    (match) => replacements[match]
  );
}

console.log(removeAccents3('àèbgòè+àòètrysàùì')); //aebgoe+aoetrysaui
// Performance : 69059.40 ops/s

I have come up with a few approaches that deliver similar performances. The RegExp replace method stands out as the most efficient, especially with longer strings where it shows a performance boost of over 20%.

const accents = [
  {
    val: 'à',
    repl: 'a',
  },
  {
    val: 'è',
    repl: 'e',
  },
  {
    val: 'ì',
    repl: 'i',
  },
  {
    val: 'ò',
    repl: 'o',
  },
  {
    val: 'ù',
    repl: 'u',
  },
];

const removeAccents = (text) => {
  for (const a of accents) text = text.replace(new RegExp(a.val, 'ig'), a.repl);
  return text;
};

console.log("First test:", removeAccents('àèbgòè+àòètrysàùì')); //aebgoe+aoetrysaui
// Performance : 46168.04 ops/s

// 2

const accents2 = {
  à: 'a',
  è: 'e',
  ì: 'i',
  ò: 'o',
  ù: 'u',
};
const removeAccents2 = (text) => text.split("").map(c => accents2[c] ? accents2[c] : c).join("")

console.log("Second test:", removeAccents2('àèbgòè+àòètrysàùì')); //aebgoe+aoetrysaui
// Performance : 45910.35 ops/s

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

Assign the value from the list to a variable in order to execute an API call

Imagine a scenario where there's a button that displays a random joke based on a specific category. The categories are fetched using an API request from https://api.chucknorris.io/jokes/categories The jokes are generated from https://api.chucknorris. ...

Tips on adjusting the label size of a radar chart in chart.js

My radar chart labels are appearing skewed and messed up on mobile devices, so I decided to scale them using the following code within ComponentDidMount(): const plugins = [{ beforeDraw: function(c) { var chartHeight = c.chart.height; c ...

You can definitely invoke a function within a React hook

This code snippet showcases a component utilizing Hooks in React Native import React, { useEffect, useState } from 'react'; import { StyleSheet, Text, View, TouchableOpacity, Animated } from 'react-native'; import CAStyles fro ...

Retrieve the ReadStream from Firebase Storage and provide it as input to the Openai API

I am struggling to retrieve an image from firebase storage and transmit it to an openai endpoint Here is my current code snippet: const fileStorage = await getStorageAdmin(uid, "/sample.png"); const file = fileStorage.createReadStream(); co ...

Tips for preventing the playback of the sound while recording

When creating a basic JavaScript application that involves opening a stream from the user and analyzing frequencies, I found that while Google Chrome and Opera work well by providing feedback in the headphones, Firefox often remains silent. Additionally, F ...

Expo: A guide on integrating expo code into an existing Android project

I'm looking to enhance my Android app (which is built in standard Java) by allowing users to create their own 3D models. To achieve this, I want to incorporate a 3D viewer within the app so that users can view and interact with their creations. My pl ...

Remove the initial section of the text and provide the rest of the string

I am a beginner in the world of Javascript and unfortunately I have not been able to find an answer to my current problem. Here is the situation. On a webpage, I am receiving a URL that is sometimes presented in this format: http://url1.come/http://url2.c ...

iterating over a nested map within a map in an Angular application

I wrote a Java service that returns an observable map<k, map<k,v>> and I'm currently struggling to iterate through the outer map using foreach loop. [...] .then( (response: Package) => { response.activityMap.forEach((key: s ...

What is the process for converting a file to base64 encoding, and then uploading it as a multipart file to a backend API using JavaScript

I am working on a project to create a micro-service that can receive base64 encoded data. However, when attempting to send more than 6 MB of data, I encountered the following error message: The multi-part request contains parameterized data (excluding ...

Learn how to showcase the current date by utilizing JavaScript arrays and the getDate method!

I have been struggling to format the date as follows: "Today is Sunday, the 31st day of March in the year 2019." I am working with JavaScript in an HTML5 document. Below is the code I have so far, and I would appreciate any help. I prefer not to rely on ...

What could be causing my code to retrieve duplicate items every time the page is loaded?

Currently, I'm diving into the world of React and attempting to fetch product data for a list. The goal is to initially fetch 2 items and then load 2 more items when a button is clicked. However, the issue I'm facing is that it's fetching t ...

JavaScript multiplying an array in HTML

Snippet of HTML code <input name="productCode[]" value="" class="tInput" id="productCode" tabindex="1"/> </td> <input name="productDesc[]" value="" class="tInput" id="productDesc" readonly="readonly" /></td> <input name="pr ...

I'm looking for assistance on how to set the minimum height using jQuery. Can anyone provide

My attempt to use the minHeight property in one of my divs is not successful, and I am unsure why... <div id="countries"> <div class="fixed"> <div class="country" style="marging-left:0px;"></div> <div class="country"&g ...

Querying escape characters from JSON to JavaScript

When trying to stringify quotes (' and "), it is necessary to escape them. However, the following results in Firebug can be puzzling: 1. >> JSON.stringify({foo: "a"a'a'}); SyntaxError: missing } after property list Interpretation: Th ...

Should I utilize Next.js API route or communicate directly with Firestore from the client side?

Greetings, I am new to Next.js and have a few queries regarding utilizing Firebase authentication on both the client side and server side. My project is set up with Firebase admin and client SDKs, and I have a signup page where users provide their name, em ...

How can I prevent query string parameters from being sorted in React Router?

I'm having trouble setting a Route path with a query string using react-router. The issue is that react-router always arranges query params alphabetically, resulting in a sorted query string in the URL. For instance, on a location filter page where I ...

Is it possible to navigate to an HTML element in the template of a different component?

One of my components contains a navigation bar with a function that allows users to scroll to a specific element on the page. Here is the template for the Navbar: <a class="nav-link" (click)="scroll(services)">Services</a> The code for the N ...

Developing uniform resource locators with jQuery

As I work on developing my webapp, I have made use of the tag in my JSPs to ensure that all links within the application - whether they lead to pages or resources like images and CSS - always stem from the root directory rather than being relative to the ...

Encountering Issues with Route Query Parameters in Nuxt/Vue Template using TypeScript

I am currently working on a Nuxt.js project with TypeScript and am facing an issue with route query parameters. The specific problem arises when TypeScript throws a type error related to a route query parameter called userType. The issue occurs when I att ...

Enable or disable options with the user's permission

Currently, I am developing a WordPress plugin that will display a simple div on all pages. The code is set up to create the div, turn it into a shortcode, and then show it on each page. I want to include a checkbox in the admin settings so that users can ...