0

I am kind of new to regex, and haven't used it much before.

I am trying to match the following string String A and replace it to String B

String A:

+ ANYTHING_NO_SPACES.prototype.ANYTHING_NO_SPACES = function()
{
    ANYTHING
}

String B:

ANYTHING_NO_SPACES.prototype.function_segments.ANYTHING_NO_SPACES.push(function())
{
    ANYTHING
})

ANYTHING_NO_SPACES means anything can be put there with no spaces

ANYTHING means anything can be put there, spaces etc.

I also would like to ignore new lines, so a new line would be the same thing as a space or nothing.

EDIT: Here's what I've got so far:

(\+ \w+.prototype\.\w+ = function\(\)( |\n){([\S\s]*?)})

I can't figure out how to finish the last bit.. changing to string into string b

Any ideas on how to finish that?

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
David Callanan
  • 5,601
  • 7
  • 63
  • 105

1 Answers1

1

Here's how you can do it:

var output = input.replace(
  /(^|\n)\s*\+\s*(\w+)\.prototype\.(\w+)\s*=\s*function\(\)\n{([\s\S]+?\n})/g,
  "$1$2.prototype.function_segments.$3.push(function())\n{$4)"
);

A few things worth noticeable in that regular expression:

  • (^|\n) is either the start of the string or a new line
  • [\s\S] matches any character including a new line
  • [\s\S]+? is non greedy so that it doesn't capture several functions in one go
  • this can work only if your code is properly indented: as the code isn't parsed we rely on a } being at the start of the line to detect the end of the function

Demonstration:

document.getElementById("output").innerHTML = document.getElementById("input").innerHTML.replace(
  /(^|\n)\s*\+\s*(\w+)\.prototype\.(\w+)\s*=\s*function\(\)\n{([\s\S]+?\n})/g,
  "$1$2.prototype.function_segments.$3.push(function())\n{$4)"
);
INPUT:
<pre id=input>
+ ANYTHING_NO_SPACES.prototype.ANYTHING_NO_SPACES = function()
{
    ANYTHING
}
+ blabla.prototype.hop = function()
{
    ANYTHING
    TOO
}
</pre>
OUTPUT:
<pre id=output>
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758