1

I have a piece of code that looks for links and puts them into an onClick event:

var regex = /href\s?=\s?"\s?([\S]+)"/g;
var newText = $sanitize(text).replace(regex, "onClick=\"window.open('$1', '_system', 'location=yes')\"");

The only issue is that for particularly long links it looks like a newline is probably added because when I try to click on the links the expected result doesn't happen (I also copy and paste the links into my text editor and there appears to be a line break). Here is an example of the link:

window.open('http://somedomain.com/subscription/some-report-text/issue/the-deadliest-word-on-the-
planet-could-bring-savvy-investors-extraordinary-profits/?u=000071340856&vid=TatDiU&a=MMP&o=9637385?u=000071340856&vid=8ALdFM&a=MMP&o=6530827?u=000071340856&vid=9Vm2j_&a=MMP&o=1652570?u=000071340856&vid=Cd_ME9&a=MMP&o=8995371', '_system', 'location=yes')

Is there another regular expression I can run to get rid of line breaks from within my new links? Or is there something wrong with my first expression?

p.s. what is the secret to learning regular expressions?

miken32
  • 42,008
  • 16
  • 111
  • 154
David Jarrin
  • 1,635
  • 4
  • 19
  • 40
  • The secret to learning regular expressions is to understand that they are not a universal tool and [should not be used to parse markup languages](http://stackoverflow.com/q/1732348/1255289). – miken32 Apr 13 '17 at 21:19
  • The other secret is to understand and appreciate jzw's famous quote from the 1990s. "Some people, when confronted with a problem, think 'I know, I'll use regular expressions.' Now they have two problems." – miken32 Apr 13 '17 at 21:22

2 Answers2

0

You should be parsing the DOM properly to find links. Assuming you have jQuery loaded, this is as simple as:

$("a").on("click", function(e){
    e.preventDefault();
    window.open(this.href, '_system', 'location=yes');
});

Otherwise native DOM methods will work (though it's been years since I've used them, so take this with a grain of salt.)

var links = document.getElementsByTagName("a");
for (var i = 0; i < links.length; i++) {
    links[i].addEventListener("click", function(e) {
        e.preventDefault();
        e.stopPropagation();
        window.open(e.target.href, "_system", "location=yes");
    });
}
miken32
  • 42,008
  • 16
  • 111
  • 154
-1

Fix you regex like this to match full link : href\s?=\s?"\s?([\S\s]+)"

Demo

But you should do this before : text = text.replace(/\s/, '')

or $sanitize(text.replace(/\s/, '')).replace(...)

Stephane Janicaud
  • 3,531
  • 1
  • 12
  • 18