javascriptregexstring

get the string between starting character(s) and ending character(s)


below I have given a simple string. It is just as example string, the pattern may remain the same but the string itself may change.

Input : {#Hi#}, Please {#don't#} {#mark#} this {#question#} as {#duplicate#}.

The output should be: "Hi", "don't", "mark", "question", "duplicate"

I have tried other approach in JS such as below. The below code has been added just for an example. Please refer to the input and output for your clarity.

function extractString(template, initChar, finalChar) {
  let i = 0;
  let data = [];
  do {
    if (template[i] == initChar) {
      for (let j = i + 1; j < template.length; j++) {
        if (template[j] == finalChar) {
          data[data.length] = template.slice(i + 1, j);
          i = j + 1;
          break;
        }
      }
    }
  } while (++i < template.length);
  return data;
}

extractString(
  "#adj#, #brown# fox jumps over the lazy #dog# new one.",
  "#",
  "#",
);

But the above works only for a single character.

Any help would be appreciated. Thanks.


Solution

  • Refer to the answer from Luke Garrigan, here is the sample code:

    let str = `{#Hi#}, Please {#don't#} {#mark#} this {#question#} as {#duplicate#}.`
    let matches = str.match(/(?<={#)(.*?)(?=#})/g)
    console.log(matches)