Using Regular Expressions (or not) in Javascript/Jquery to append <span> around vowels

Seeking guidance as a beginner in the coding world.

Currently, my code generates numbers from 1 to 99 and displays text next to the number based on certain conditions. For instance, numbers divisible by 3 are labeled 'Java', those divisible by 5 are labeled 'Script', and if they meet both conditions, it displays 'JavaScript'.

My current objective is to have a pop-up display the corresponding number when a user clicks on a vowel. For example: a = 0, e = 1, i = 2, o = 3, and u = 4. Therefore, upon clicking any of these vowels, the pop-up should show the respective number.

I've experimented with using regex to identify the letter 'a' and replacing it with 44 as a test. Research suggests that enclosing these vowels in a span element and adding a mouse click event would be the optimal solution. However, I'm uncertain about how to detect the vowels and wrap them in the desired manner.

Any help or guidance on this matter would be highly appreciated. Thank you all for your support.

<!DOCTYPE html>
<html>
<head>
<script src="jquery-1.9.1.min.js"></script>
</head>
<body>

<p id="demo"></p>

<script>

(function() {

    function getContent(i, str, match, replaceFn) {
        //find the vowels and wrap them in a span
        //span will have ID or class that we can attach a click handler to.
        var straeiou = "<p>" + i + " <span class='foo'>" + str + "</span></p>";
        var vowela = /a/gi;
        var newvowela = straeiou.replace(vowela, "44");

        document.write(newvowela);

    }

    function num() {
        for (var i=1; i<100; i++) {

            if (i%3==0 && i%5==0) {
                $('#demo').append(getContent(i, "JavaScript"));
            }
            else if (i%3==0) {
                $('#demo').append(getContent(i, "Java"));
            }
            else if (i%5==0) {
                $('#demo').append(getContent(i, "Script"));
            } 
            else {
                $('#demo').append(getContent(i, ""));
            }
        }
    }
    num();

    // $('aeiou').click(function() {
        // alert('clicked');
    // });
}());

</script>
</body>
</html> 

Answer №1

Firstly, your code appears to be quite disorganized and is currently not functioning properly.

You are utilizing jQuery's .append() method to add the output generated by your function getContent(), but at this moment getContent() does not return anything.

Instead of using document.write which replaces the entire content of the page, it is advisable for beginners to avoid it altogether. This method is outdated and comes with various disadvantages.

Your approach to replacing the letter a results in replacing everything within your HTML, leading to a current output similar to:

<p>3 <sp44n cl44ss='foo'>J44v44</sp44n></p>

Lastly (on a minor note), your function includes two unused parameters (match and replaceFn).

To address this issue, the primary question to ask yourself is: Why do you feel the need to use regular expressions? In this simple scenario, it might be more straightforward to directly include the spans within the string literals you are working with, like so:

$('#demo').append(getContent(i, "J<span>a</span>v<span>a</span>"));

Answer №2

To highlight the vowels, you can wrap them in a span by using the code snippet below:

$("#content").html(
    $("#content").html().replace(/(a|e|i|o|u)/ig, "<span>$1</span>")
);

Next, you can implement a click event for all span elements within the #content section to determine the corresponding values of the letters. It's advisable to store the mappings in an object for easy retrieval like this:

var vowelMapping = {
    a: 1,
    e: 2,
    i: 3,
    o: 4,
    u: 5
};

alert(vowelMapping["a"]);
// This will display 1

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

Could really use some guidance with understanding yield (and possibly promises?)

When working on a client Node.js application, I encountered a need to "wait" for the completion of an http.request. Here is an example: console.log('Before http request') responseData = x.exec(parms) console.log('Process data') Module ...

When a user clicks on a specific element's id, the image will rotate accordingly

When the elements in ul are clicked, the image rotates. The default position of the image is already rotated by a certain number of degrees, and on each click, it rotates to the desired value. This was achieved using the following code: $("#objRotates"). ...

Having trouble with jQuery's .stop() not working properly while trying to implement an effect

I have a question regarding my jQUery code: setInterval(function() { var grayarrow = jQuery("ul#dropdowngray").parent(); var greenarrow = jQuery("ul#dropdown").parent(); grayarrow.effect('shake', { times:2 }, 100); greenarrow. ...

What is the best way to choose the parent element when the child element is checked?

I am looking to customize my CheckBox. Below is the code I have written: <div class="check-box-input"> <input type="checkbox"> </div> I also want to add a style to the parent div when the input is checked. This is the code I tried, ...

Avoid clicking on links while the webpage is still loading

I am facing an issue with my website where I need to intercept link-clicking events using jQuery. Everything works fine, but there is a problem if a user clicks on a link before JavaScript finishes loading, causing it to redirect to another page in error. ...

Text placed over a video player

I have created a full-screen div with a video playing in the background and I need to overlay some HTML on top of it. However, when I add the HTML elements, they briefly appear and then disappear once the video starts playing. What could be causing this i ...

Zeroclipboard will fail to copy the text

I seem to be encountering an issue with the Zeroclipboard system. I suspect there might be an error in my code. Even though it indicates that the content has been copied, it actually hasn't been. The code I am currently using is as follows: <scri ...

Assistance needed in keeping an image with absolute positioning CSS fixed to the top left corner of the browser

Looking for some CSS help as a beginner here! I've been trying to position a transparent PNG image over a centered table, but it seems stuck in the upper left corner of the browser. Absolute positioning should give me freedom to move it around, right? ...

Discover an element using Python Selenium

Can someone assist me in finding a way to click on an image using Python's Selenium? I am trying to locate a div with the class "A" that contains another div with the class "B", and then, click on the img within the div with the class "D" <di ...

Enhance Your Search Bar with Ajax and JQuery for Dynamic Content Updates

My goal is to create a search bar that dynamically loads content, but I want the actual loading of content to start only after the user has finished typing. I attempted a version of this, but it doesn't work because it doesn't take into account ...

Try rotating a triangle in 3D using either CSS or JavaScript

I want to create a right-angle triangle that looks like this . . . . . . . . . . . . . . . . . . but I also want to add a 3D animation that will transform it into a right angle like this . . . . . ...

Utilizing TypeScript Class Inheritance: The Reference to 'super' is Only Allowed in Members of Derived Classes or Object Literal Expressions

We have encountered a scoping issue while using TypeScript classes with inheritance. It seems that TypeScript/JavaScript does not allow us to use 'super' within a promise structure or an enclosed function. The error message we are getting is: Ty ...

AngularJS ngAnimate triggering prematurely

In the current setup, p2 animates in while p1 is still animating out. After that, p1 disappears and p2 glitches up the page. The desired effect is for 1 to fade out and then have 2 fade in. html: <nav> <a ng-click="changeView('p1' ...

Iterate over the array and eliminate any stylesheets

Currently working on a website using WordPress, and dealing with some unwanted css files that come with certain plugins. I've been attempting to remove these stylesheets with JavaScript but keep running into an error saying Failed to execute 'qu ...

capturing images of web elements and a three-dimensional scene created with Three.js

Is there a way to capture and save a screenshot of a page that includes all HTML content as well as a Three.js scene? I've tried using html2canvas, but it only captures HTML elements. I also attempted to use the following code to take a snapshot of th ...

Vuetify: the item-text attribute causing issues with v-combobox

As I embark on my journey with Vue.js and Vuetify, I've encountered a simple issue with the v-combobox component that has me stumped: Picture this scenario: I want a combobox that offers three distinct options. The code snippet below functions perfec ...

Incorporate a vertical scrollbar in the tbody while keeping the thead fixed for smooth vertical scrolling

I'm seeking a solution to implement horizontal and vertical scroll for my table. Currently, the horizontal scroll is working fine, but when trying to add vertical scroll, the table header also moves along with it. Is there a way to keep the table hea ...

Is TinyMCE creating unexpected <g> tags?

When I save content in the TinyMCE WYSIWYG editor, I notice that the HTML tag below keeps appearing throughout the text: <g class="gr_ gr_283 gr-alert gr_spell gr_run_anim gr_inline_cards ContextualSpelling ins-del multiReplace" id="283" data-gr-id="28 ...

Center column with header and footer flanking each side

Trying to replicate the layout of the Facebook Android app on my page. The app features a 3 column design, with the central column exclusively displaying the header (no footer included, although I require one for my version). This visual representation is ...

What is the best way to export Class methods as independent functions in TypeScript that can be dynamically assigned?

As I work on rewriting an old NPM module into TypeScript, I encountered an intriguing challenge. The existing module is structured like this - 1.1 my-module.js export function init(options) { //initialize module } export function doStuff(params) { ...