1

I have a script that searches through urls and looks for a certain domain name, then appends some parameters to the end of the url. However, if run more than once, it will add duplicate parameters to the same url. Is it possible check if the url already has parameters on it?

JSFiddle

original stackoverflow post

code being modified

<div id="wp-content-editor-container" class="wp-editor-container"><textarea class="wp-editor-area" rows="10" tabindex="1" cols="40" name="content" id="content">&lt;a title="Link to test domain" href="http://www.domain.com"&gt;Link to google&lt;/a&gt;
&lt;a href="http://google.com/directory/subdirectory/index.html"&gt;This is another link&lt;/a&gt;
&lt;a href="http://domain.com/directory/index.html"&gt;This is a 3rd link&lt;/a&gt;

&lt;a href="http://www.domain.com/subdir?parameter"&gt;this url already has parameters&lt;/a&gt;</textarea></div>

jquery script

var url = 'www.domain.com';
var append = '?parameter';

$(".wp-editor-area").each(function() {
    $(this).text(urlify($(this).text()));
});

function urlify(text) {
    var urlRegex = /(\b(https?|ftp|file):\/\/[www.domain.com][-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
    return text.replace(urlRegex, function(url) {
        return url + append;
    })
}

current output

<a title="Link to test domain" href="http://www.domain.com?parameter">Link to google</a>
<a href="http://google.com/directory/subdirectory/index.html">This is another link</a>
<a href="http://domain.com/directory/index.html?parameter">This is a 3rd link</a>

<a href="http://www.domain.com/subdir?parameter?parameter">this url already has parameters</a>

The ideal output would not add a second "?parameter" at the end of the url ^

Thanks!

Community
  • 1
  • 1
  • isn't this just a matter of checking if the parameter string is in the full url or not? If it is then don't add it, else add parameter – Huangism Jul 11 '12 at 20:32

1 Answers1

2

I think you can use indexOf to check if the URL already contains what you are trying to append.

  function urlify(text) {
                var urlRegex = '/(\b(https?|ftp|file):\/\/[www.domain.com][-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig';
                return text.replace(urlRegex, function (url) {
                    // if the url does not contain append, concat append to the URL
                    if (url.indexOf(append) == -1) {
                        return url + append;
                    }
                    return url;
                });
james31rock
  • 2,615
  • 2
  • 20
  • 25
  • i was mistaken earlier and deleted the comment. Original answer works beautifully thank you! Much easier than searching through the url. – DirkDiggler Jul 11 '12 at 21:12