Chris Riley
Chris Riley

Reputation: 1408

Javascript Regex only replacing first match occurence

I am using regular expressions to do some basic converting of wiki markup code into copy-pastable plain text, and I'm using javascript to do the work.

However, javascript's regex engine behaves much differently to the ones I've used previously as well as the regex in Notepad++ that I use on a daily basis.

For example- given a test string:

==Section Header==
===Subsection 1===
# Content begins here.
## Content continues here.

I want to end up with:

Section Header
Subsection 1
# Content begins here.
## Content continues here.

Simply remove all equals signs.

I began with the regex setup of:

var reg_titles = /(^)(=+)(.+)(=+)/

This regex searches for lines that begin with one or more equals with another set of one or more equals. Rubular shows that it matches my lines accurately and does not catch equals signs in the middle of contet. http://www.rubular.com/r/46PrkPx8OB

The code to replace the string based on regex

var lines = $('.tb_in').val().split('\n'); //use jquery to grab text in a textarea, and split into an array of lines based on the \n 
for(var i = 0;i < lines.length;i++){
  line_temp = lines[i].replace(reg_titles, "");
  lines[i] = line_temp; //replace line with temp
}
$('.tb_out').val(lines.join("\n")); //rejoin and print result

My result is unfortunately:

Section Header==
Subsection 1===
# Content begins here.
## Content continues here.

I cannot figure out why the regex replace function, when it finds multiple matches, seems to only replace the first instance it finds, not all instances.

Even when my regex is updated to: var reg_titles = /(={2,})/

"Find any two or more equals", the output is still identical. It makes a single replacement and ignores all other matches.

No one regex expression executor behaves this way for me. Running the same replace multiple times has no effect.

Any advice on how to get my string replace function to replace ALL instances of the matched regex instead of just the first one?

Upvotes: 1

Views: 303

Answers (3)

Add the g modifier to do a global search:

var reg_titles = /^(=+)(.+?)(=+)/g

Upvotes: 2

TML
TML

Reputation: 12966

Your regex is needlessly complex, and yet doesn't actually accomplish what you set out to do. :) You might try something like this instead:

var reg_titles = /^=+(.+?)=+$/;
lines = $('.tb_in').val().split('\n');
lines.forEach(function(v, i, a) {
    a[i] = v.replace(reg_titles, '$1');
})
$('.tb_out').val(lines.join("\n"));

Upvotes: 1

vks
vks

Reputation: 67968

^=+|=+$

You can use this.Do not forget to add g and m flags.Replace by ``.See demo.

http://regex101.com/r/nA6hN9/28

Upvotes: 3

Related Questions