-1

I have a form, where users are to insert musical chords as [Am], [D], etc inside a textarea. A chord letter enclosed by brackets.

I want to prevent users from entering northern europian variations of [H], and have them replaced by english [B] on form submit.

How can I set up a replace function that does something like this:

[H] -> [B]
[Hm] -> [Bm]
[Hm7] -> [Bm7]
[h] -> [H]
[h7] -> [H7]

I should be enough to globally replace H/h inside a bracket with a capital B inside the same bracket.

Is there a smart replace function you would recommend?

Filip Blaauw
  • 731
  • 2
  • 16
  • 29
  • 2
    Did you try to write something yourself? What do you mean by "smart replace"? What is the problem with a regular string-replace function? – Dekel Oct 15 '16 at 20:40
  • By smart I mean the most efficient way to write a string replace function – Filip Blaauw Oct 15 '16 at 20:41
  • Several ideas for performing multiple string replacements have been submitted [here](http://stackoverflow.com/questions/5069464/replace-multiple-strings-at-once). – trincot Oct 15 '16 at 20:45

2 Answers2

0

You could use this replace() call:

.replace(/\[H(.*?)\]/gi, '[B$1]')

Snippet:

document.forms[0].onsubmit = function() {
    var txt = document.querySelector('textarea');
    txt.textContent = txt.textContent.replace(/\[H(.*?)\]/gi, '[B$1]');
}
<form action="#">
  <textarea>test [H] and [H7m], but also [h] and [h7].</textarea>
  <input type="submit" value="Submit">
</form>
trincot
  • 317,000
  • 35
  • 244
  • 286
0

What you're looking for is called a Regex--short for regular expression. It allows you to search for (and replace) patterns instead of just literal strings.

To match an H chord you can use /\[[Hh]([^\]]*)\]/g. This means:

  • /: Marks the start of a regex (like " to denote the start of a string)
  • \[: Match a literal [
  • [Hh]: Match either H or h
  • (...) Capture group: match everything inside and store it for later
    • [^\]]: Match anything that isn't ]
    • *: Match the last character zero or more times (zero or more characters that aren't ]
  • \]: Match a literal ]
  • /: Marks the end of the regex (like " to close a string)
  • g: Global modifier. Makes the regex match every occurance in the input, not just the first one.

Demo

To use this, use the replace function on the input string:

inputstring.replace(/\[[Hh]([^\]]*)\]/g, "[B$1]");

The $1 in the replacement value inserts the value capturing group in the regex.

3ocene
  • 2,102
  • 1
  • 15
  • 30