javascriptjqueryarraysvarguitar

Check if any word from text matches an array


I want to achieve the following:

1) Check every word from a textarea if it is a guitar chord.

To do that, I created an array which contains all characters that guitar chords have (if a word matches the characters from this array it is a guitar chord):

var Regex = /^\s*(?:(A|B|C|D|E|F|G|A#|C#|D#|F#|G#|Ab|Bb|Db|Eb|Gb){1}(?:m|\+|\-|aug|dim|add|b|#|1|2|3|4|5|6|7|8|9|0|\/)*\s*)+$/;

2) If a word matches, I want it to become a link, pointing to an URL customized by the word itself.

e.g. The following line

Am   Bb  C# Dadd9
Song lyrics here

should turn into

<a href="example.com/Am">Am</a>   <a href="example.com/Bb">Bb</a>  <a href="example.com/C#">C#</a> <a href="example.com/Dadd9">Dadd9</a>
Song lyrics here

And here's what I've com up to for step 2:

var link = "http://www.example.com/";
      $.each(chord, function(index, value) {   //append link to chord
        $('.output').append('<a href="' + link + value + '">' + value + '</a> ');
      });

But I need to define "chord". How can I do to check each word, then if it is a chord (matching "Regex" characters) append link?


Solution

  • Here is a distilled version of @GuyWaldman's approach.

    What this does is to generate the HTML elements dynamically instead of using an object.

    var chordPattern = /(?:(A|B|C|D|E|F|G|A#|C#|D#|F#|G#|Ab|Bb|Db|Eb|Gb){1}(?:m|\+|\-|aug|dim|add|b|#|1|2|3|4|5|6|7|8|9|0|\/)+)/g;
    var str = `Am   Bb  C# Dadd9
               Song lyrics here`;
    var html = str.replace(chordPattern, function(value){
        return "<a href='https://example.com/"+value+"'>"+value+"</a>";
    });
    document.write(html);

    You may need to adjust the regex because I'm not sure if it will match all possible chords or if it matches only chords. You will also have to find a way to deal with the special characters in the URLs