How can I use javascript regular expressions to replace them if certain characters are included?

Asked 2 years ago, Updated 2 years ago, 71 views

String.replace(/case/gi, "FIND!")

As above, I wrote to change the string case to FIND! without being case-sensitive.
If there are two strings, > and < on both sides of case, how do I write it so that it does not replace?

For example, case in a sentence will be changed to FIND!, but I don't want to change case wrapped in ><tag>.

python javascript jquery html flask

2022-09-21 10:07

1 Answers

I think we need to find the regular expression you want by limiting the specific number of cases. Because the essence of the problem is 'excluding text wrapped in tags', bad luck can make it much more complicated.

To consider the most convenient case, the regular expression below captures one character each other than > and and < attached to the string case and reattaches it to the front and back of FIND!. The key is the [^abc] syntax.

const regex = /(([^>])case([^<]))/gi;
const subst = `$2FIND!$3`;

const str = `<h3><span>Case</span> Closed</h3>
<p>Detective Conan series seems to be called "Case Closed" in English.</p>`;
console.log(str.replace(regex, subst));

Investigate this and that and apply it.


2022-09-21 10:07

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.