In JavaScript, find a value in an array and substitute it with the value from the

One of my tasks involves manipulating a string variable in the following manner:

domNodes += '<a href="javascript: void(0);" data-role="node_jump" data-node="'+this.tagName.toLowerCase()+'">'+this.tagName + "</a>" + " &raquo; ";

In addition, I am working with an array that contains a 2D array. The first element is the string to be identified and the second element is the replacement string:

var replaceTags = [["i", "em"], ["b", "strong"]];

Essentially, I need to replace certain tags based on predetermined rules. For example, if this.tagName matches i, it should be replaced with em. This also applies to b and strong.

I have successfully accomplished this task in the past, but unfortunately, I cannot recall the exact method right now.

Answer №1

http://jsfiddle.net/Ab12Cd/

var swapElements = [["u", "ins"], ["s", "strike"]];
var elName = this.elementName;
for (var x = 0; x < swapElements.length; x++) {
    elName = elName.replace(new RegExp(swapElements[x][0], 'g'),swapElements[x][1]);
}

Answer №2

One way to achieve this is by defining a custom function:

function tagReplacer(tagName) {
    var tags = [["i", "em"], ["b", "strong"]];
    for(var i = 0; i < tags.length; i++) {
        if(tags[i][0] === tagName) return tags[i][1];
    }
    return tagName;
}

To use the function, you can do:

data-element="'+tagReplacer(this.tagName.toLowerCase())+'"

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

Difficulty with formatting decimal points in JavaScript

I seem to be having an issue with decimal places in my code. Currently, it's showing the result as 123 123 12 but I actually need it to be displayed as 12 312 312. Is there anyone who can assist me with formatting this correctly? Here is the section ...

Unraveling the mysteries of an undefined entity

When the variable response is undefined, attempting to retrieve its property status will result in an error: Error: Unable to access property 'status' of undefined const { response, response: { status }, request, config, } = error as A ...

How to efficiently manage multiple INSERT, SELECT, and UPDATE operations in mysql2 using nodejs

I am seeking guidance on how to approach a specific problem that I am facing. Due to my limited knowledge of databases, I am unsure of the best method to tackle this issue. The challenge I am dealing with involves receiving a 'large' amount of d ...

Getting JSON data from an API using $.ajax

Currently, I am working on creating a random quote machine. To start off, I wrote the following HTML code to outline the necessary elements: <div id="quoteDisplay"> <h1 id="quote">Quote</h1> <h2 id="author">- Author</h2> ...

Material-UI web application experiencing crashes due to worn-out cards, resulting in element type being declared as invalid and raising an error

After reviewing numerous similar SO questions, it appears that the issue always comes down to problems with imports. Typically, these involve mistyped import destinations or missing braces, but I have double-checked and found no such issues in my code. ht ...

What is the process for invoking a page using a JavaScript function?

My index.php has a javascript code that calls a page in the following way: id = 5; var url = 'pages/pg/'+id+'/'; f.action = urlss.toLowerCase(); return true; The issue arises when I try to call the same page with a different ID, it do ...

What are the steps to modify data within the root component?

I am currently working on a Vue project with vue-cli and routes. In my App.vue file, the template structure is as follows: <template> <div id="app"> {{Main}} <router-view></router-view> </div> </template&g ...

"Ensuring Username Uniqueness in AngularJS and CakePHP3: A Step-by-Step

<input type="email" id="username" dbrans-validate-async="{unique: isUsernameUnique}" ng-model="username" required class="form-control" name="username"> $scope.isUsernameUnique = function(username) { $http.get(url+'/isUsernameUnique&apo ...

Embedding a string within an image source attribute in VueJS

My goal is to extract the name of a job department as data for a Vue component, convert it to lowercase, and then use it to dynamically render the correct image based on the department's name. The images are named after the departments. The current c ...

Assign a value to a text input using React

Whenever the closeEmail function is triggered or called, I need to set the email.emailAddress as the value of the textfield. I'm fairly new to React, what is the syntax or method to achieve this? Any suggestions? #code snippet <div style={{ disp ...

Employing jQuery with dynamic content within this context

Can anyone help me with jQuery and dynamic content? I'm trying to prepend items to a list and show the contents of a specific item when clicked, but all items' content is being displayed instead. I attempted using (this) without success. $(docum ...

Tips for ensuring that an Ajax request successfully executes when a page loads

I have a question about implementing an AJAX request in my code. Currently, I have the text on the screen updating when a dropdown input is selected using 'onchange'. However, I also want this same behavior to occur on page load, but I am struggl ...

Ways to incorporate vector .svg images into a D3js tree diagram

var treeData = [ { "name": "Top Level", "parent": "null", "remark":"yes", "children": [ { "name": "Level 2: A", "parent": "Top Level", "remark":"yes", "children": [ { "name": "So ...

Assigning numpy array values to an integer-indexed flat slice

During my journey to master numpy, I delved into writing code that implements LSB (steganography) encryption: def str2bits_nparray(s): return np.array(map(int, (''.join(map('{:07b}'.format, bytearray(s))))), dtype=np.bool) def LSB ...

Hide the address bar in a Google Maps iFrame

After numerous attempts, I still can't seem to hide the address bar on this Google Maps iFrame. Can anyone provide a solution or workaround for this issue? https://i.sstatic.net/x0pl9.png I have tried using display:none; in our CSS, which successfull ...

selecting arrays within arrays according to their date values

With an array of 273 arrays, each containing data about a regular season NFL football game, I am looking to categorize the games by week. In total, there are 17 weeks in the NFL season that I want to represent using separate arrays. The format of my array ...

After creating a new Packery using AngularJS, the getElementById function may return null

Alright, so I've got this HTML markup: <button ng-click="create()">create list</button> Every time I click it, I create a new list using the Packery jQuery plugin. app.directive('packery', ['$compile', function($com ...

An issue occurred while evaluating the Pre-request Script: Unable to access the 'get' property of an undefined object

I need help accessing the response of my POST request in Postman using a Pre-request Script. Script below : var mobiles = postman.environment.get("mobiles"); if (!mobiles) { mobiles =["8824444866","8058506668"]; } var currentMobile = mobiles. ...

Triggering the Bootstrap modal multiple times with each increment

I am experiencing an issue with Bootstrap Modal where the action fires up multiple times upon clicking. <div id="loginModal" class="modal fade"> <div class="modal-dialog"> <div class="modal-content"> ... & ...

Tips for choosing a unique item from a list of values during each iteration of a loop in Python

Essentially, my goal is to retrieve a new item from a list every time I access that list. The structure of my list is as follows: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c2b6a7b1b6a7afa3abaee9f282a5afa3abaeeca1adaf"> ...