4

I'm trying to write a regular expression for following criteria

The source string might optionally contain an html code. Which should be preserved, everything outside tag should replace with a static text.

function replaceCode( mystring ){
    var replaceWith = "Hello!!!" ;
    //do something with mystring here..
}

var string1 = "<span>Title</span> A small note" ;
var string2 = "Another big note" ;

alert( replaceCode(string1) ) ;
alert( replaceCode(string2) ) ;

Resultant strings must be

//string1 must become
<span>Title</span> Hello!!!

//string2 must become
Hello!!!
nithinTa
  • 1,632
  • 2
  • 16
  • 32
  • Possible duplicate of [jQuery: Add element after another element](https://stackoverflow.com/questions/2244605/jquery-add-element-after-another-element) – KolaCaine Aug 28 '17 at 09:19
  • If the text outside of the span is changed to hello, then why do you need string2? – Hema Nandagopal Aug 28 '17 at 09:20
  • As regular expressions go there are different flavors and syntax based on what language you are using. You might want to clarify the context. I do see that you tagged the question with JavaScript and HTML but best to be clear. Vanilla JavaScript or are you using jQuery? – fjoe Aug 28 '17 at 09:21
  • 1
    I've used two string for demonstrating my two situations, there will be one variable only. which might be holding the value as in string1 or string2. I'm using javascript and not jquery. – nithinTa Aug 28 '17 at 09:26
  • You want to keep the text in html tag unchanged? – Sougata Bose Aug 28 '17 at 11:36
  • Yes, if there something in html tags that should remain same after replacement. – nithinTa Aug 28 '17 at 12:08

1 Answers1

0

You may do following:

var yourString = "<span>Title</span> any text to replace";
var yourReplacement = "Hello!";

//Split by html tags
var tokens = yourString.split(/<\w+>\w+<\/\w+>/);

for (var i = 0; i < tokens.lenght; i++) {
   yourString = yourString.replace(tokens[i], yourReplacement);
}

This, however, is probably not the best solution and will not work for nested tags but fit your examples.

Kloker
  • 499
  • 4
  • 14