0

As per this answer, I am making use of a replaceAll() function to swap arbitrary strings in my javascript (Node) application:

this.replaceAll = function(str1, str2, ignoreCase)
{
    return this.replace(new RegExp(str1.replace(/([\/\,\!\\\^\$\{\}\[\]\(\)\.\*\+\?\|\<\>\-\&])/g,"\\$&"),(ignoreCase?"gi":"g")),(typeof(str2)=="string")?str2.replace(/\$/g,"$$$$"):str2);
}

I would like to expand this regex, such that it does not try to match anything inside a set of <span>...</span> tags. (I need to add HTML Span tags around parts of some strings, and I don't want to wrap anything in a span twice, if the patterns would duplicate [I.e., 'Foo' and 'Foobar' in the string "Foobarbaz"])

I am running multiple regex search/replaces on a single string, and I want to make sure that nothing gets processed multiple times.

My understanding is that I'll need a [<SPAN>] ... [</SPAN>] somehow, but I'm not quite sure on the specifics. Any advice?

Community
  • 1
  • 1
Raven Dreamer
  • 6,940
  • 13
  • 64
  • 101
  • 1
    You don't need to escape symbols in character groups. – fardjad Dec 11 '13 at 19:52
  • 2
    You might want to tell us what this... piece of code is supposed to do (input->output). – georg Dec 11 '13 at 19:56
  • @thg435 Ah, fair point. Eseentially, take in some raw text, and put HTML tags (a Span with an ID) around matched patterns. The problem is, I don't want to match things that have already been wrapped in a Span. – Raven Dreamer Dec 11 '13 at 20:04
  • @fardjad Wasn't trying to; I want to avoid the html tags, which have the `/` as part of the text. – Raven Dreamer Dec 11 '13 at 20:08
  • There is a concept of look ahead and lookbehind you may have to use it. – Zeus Dec 11 '13 at 20:11

1 Answers1

1

I don't understand what your regexp does, but in general the technique is like this:

html = "replace this and this but not <span> this one </span> or <b>this</b> but this is fine"

// remove parts you don't want to be touched and place them in a buffer
tags = []
html = html.replace(/<(\w+).+?<\/\1>/g, function($0) {
    tags.push($0)
    return '@@' + (tags.length - 1)
})

// do the actual replacement
html = html.replace(/this/g, "that")

// put preserved parts back
html = html.replace(/@@(\d+)/g, function($0, $1) {
    return tags[$1]
})
georg
  • 211,518
  • 52
  • 313
  • 390