0

I need a regex that detects words inside a string. My regex works fine when the class consists of a single word, but not for multiple words.

function repl(string){
  return string.replace(/<span class="[a-z\s\-\b \b]*">/ , (n)=>{
  return <Symbol/>
}
}

Works:

repl('<span class='hi'>') /==> <Symbol/>

Does not work:

repl('<span class='hi hi'>')
tripleee
  • 175,061
  • 34
  • 275
  • 318
  • The RegExp you provided should *not* match ``, since your pattern explicitly checks for a double quote delimiter for the class string itself, not a single quote as the test case uses. – esqew Dec 07 '22 at 16:51
  • Why not use a proper (X)HTML/XML parser instead of trying to chop up markup yourself? There are *so* many edge cases with this type of markup that in almost 100% of cases it doesn't make much sense to try to roll your own parser (see [the canonical answer](https://stackoverflow.com/a/1732454/269970)) – esqew Dec 07 '22 at 16:52
  • When the test cases are adjusted to use `"` for delineating the class attribute value string, it seems that the tag is still matched by the pattern you've built. ([Regex101 demonstration](https://regex101.com/r/QHmxUk/1)) What *exactly* does "*does not work*" actually mean? Can you clarify your problem statement a bit more? See also: [ask] – esqew Dec 07 '22 at 16:54
  • Several of the items in your current attempt seem out of place. You probably tried to say something like `"[a-z\s-]*"`; what did you hope the space and the multiple `\b`s would do that `\s` doesn't? – tripleee Dec 07 '22 at 17:16
  • In addition, your code appears to contain multiple syntax errors. – tripleee Dec 07 '22 at 17:22

1 Answers1

1

You can simplify your expression to: /<span class=["'][a-z_\-][\w\s\-]*["']>/i

Make sure your HTML element attributes are double-quoted.

Note: Please be aware that the closing </span> tag is mandatory and should never be ommited.

const repl = (str) =>
  str.replace(/<span class=["'][a-z_\-][\w\-\s]*["']>/i, () => '<Symbol />');

console.log(repl('<span class="hi">'));
console.log(repl("<span class='hi hi'>"));
console.log(repl('<span class="one two  three   ">'));
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132