Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using search and replace with regex in javascript

I have a regular expression that I have been using in notepad++ for search&replace to manipulate some text, and I want to incorporate it into my javascript code. This is the regular expression:

Search (?-s)(.{150,250}\.(\[\d+\])*)\h+ and replace with \1\r\n\x20\x20\x20

In essence creating new paragraphs for every 150-250 words and indenting them.

This is what I have tried in JavaScript. For a text area <textarea name="textarea1" id="textarea1"></textarea>in the HTML. I have the following JavaScript:

function rep1() {
    var re1 = new RegExp('(?-s)(.{150,250}\.(\[\d+\])*)\h+');
    var re2 = new RegExp('\1\r\n\x20\x20\x20');
    var s = document.getElementById("textarea1").value;
    s = string.replace(re1, re2);
    document.getElementById("textarea1").value = s;
}

I have also tried placing the regular expressions directly as arguments for string.replace() but that doesn't work either. Any ideas what I'm doing wrong?

like image 702
Floran Thovan Avatar asked Oct 17 '25 01:10

Floran Thovan


1 Answers

Several issues:

  • JavaScript does not support (?-s). You would need to add modifiers separately. However, this is the default setting in JavaScript, so you can just leave it out. If it was your intention to let . also match line breaks, then use [^] instead of . in JavaScript regexes.
  • JavaScript does not support \h -- the horizontal white space. Instead you could use [^\S\r\n].
  • When passing a string literal to new RegExp be aware that backslashes are escape characters for the string literal notation, so they will not end up in the regex. So either double them, or else use JavaScript's regex literal notation

  • In JavaScript replace will only replace the first occurrence unless you provided the g modifier to the regular expression.

  • The replacement (second argument to replace) should not be a regex. It should be a string, so don't apply new RegExp to it.

  • The backreferences in the replacement string should be of the $1 format. JavaScript does not support \1 there.
  • You reference string where you really want to reference s.

This should work:

function rep1() {
    var re1 = /(.{150,250}\.(\[\d+\])*)[^\S\r\n]+/g;
    var re2 = '$1\r\n\x20\x20\x20';
    var s = document.getElementById("textarea1").value;
    s = s.replace(re1, re2);
    document.getElementById("textarea1").value = s;
}
like image 194
trincot Avatar answered Oct 19 '25 14:10

trincot