-2
var text = "This is simple html text is split by a script tag <script language='javascript'>simple simple text text <script> text.Note I want don't want to lost my original text var. I just want to replace 'simple' word with 'myword' but not inside script tag as well content of script tag";

I want to replace all 'simple' words with 'myword' in text string but not inside script tags content. I have tried but it's not working

    var searchMask = 'simple';
    var regEx = new RegExp("(" + searchMask + ")(?!([^<]+)?>)", "gi");
    var result = text.replace(regEx, "myword");

Output that I want to get:-

This is myword html text is split by a script tag <script language="javascript">simple simple text text </script> text.Note I don't want to loose my original text var. I just want to replace 'myword' word with 'myword' but not inside script tag as well content of script tag

  • Regex will create trouble while dealing with nested tags, hence I recommend you to use an html parser for solving it. – Silvanas Oct 01 '20 at 11:42
  • 1
    Does this answer your question? [RegEx match open tags except XHTML self-contained tags](https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags) (In short: don't use Regular Expressions to parse HTML, and instead use a dedicated HTML/XML parser. It will handle edge cases & other oddities much more robustly than a RegExp pattern could.) – esqew Oct 01 '20 at 14:06
  • It's not necessary to use regex. Can you provide me solution anyway. – tech giant Oct 01 '20 at 15:30

1 Answers1

-1

How about splitting this first, applying regex for the right part, and then joining again?

var splits = text.split('script');
var forRegex = splits.shift();

var searchMask = 'simple';
var regEx = new RegExp("(" + searchMask + ")(?!([^<]+)?>)", "gi");
var regexResult = forRegex.replace(regEx, "myword");

var result = [regexResult, ...splits].join('script')
pbialy
  • 1,025
  • 14
  • 26