检查文本中的任何单词是否与数组匹配

Check if any word from text matches an array

我想实现以下目标:

1) 检查文本区域中的每个单词是否是吉他和弦。

为此,我创建了一个数组,其中包含吉他和弦具有的所有字符(如果一个词与该数组中的字符匹配,则它是吉他和弦):

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) 如果一个单词匹配,我希望它变成一个link,指向一个由单词本身定制的URL。

例如下面一行

Am   Bb  C# Dadd9
Song lyrics here

应该变成

<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

这是我为第 2 步准备的内容:

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

但是我需要定义"chord"。我该如何检查每个单词,然后如果它是一个和弦(匹配 "Regex" 个字符)追加 link?

您可以使用 String.prototype.replace().

为简洁起见,假设我们要定位 AmBbC#和弦。

// create a map for the chords to the anchors
var chordsAnchorsMap = {
    "Am": "<a href='https://example.com/a-minor'>Am</a>",
    "Bb": "<a href='https://example.com/b-flat'>Bb</a>",
    "C#": "<a href='https://example.com/c-sharp'>C#</a>"
};

// regular expression for the chords
var regex = /(Am|Bb|C#)/g;

var string = "Am    Bb    C#    Bb   M    Bb";

// replace all instances of the chords with their mapped anchors
var result = string.replace(regex,
    function(capturedChord) {
        // if chord is mapped to an anchor, replace it with the appropriate anchor
        if (chordsAnchorsMap.hasOwnProperty(capturedChord)) {
            return chordsAnchorsMap[capturedChord];
        }
        // else, return the just chord itself (in other words - don't replace it)
        return capturedChord;
    }
);

现在 result 将包含:

<a href='https://example.com/a-minor'>Am</a>    <a href='https://example.com/b-flat'>Bb</a>    <a href='https://example.com/c-sharp'>C#</a>    <a href='https://example.com/b-flat'>Bb</a>   M    <a href='https://example.com/b-flat'>Bb</a>

这是@GuyWaldman 方法的精简版。

这样做是动态生成 HTML 元素,而不是使用对象。

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);

您可能需要调整正则表达式,因为我不确定它是匹配所有可能的和弦还是只匹配和弦。 您还必须找到一种方法来处理 URL 中的特殊字符