0

Its part of an exercise and the task is:

  1. If the first arg is only the url, then return the url + the second arg (which is a id number) //that works in my code
  2. If the first arg (url) includes already the id-then exchange that Id with the second arg(Id) -for example http://www.google.com?ID=111 becomes http://www.google.com?ID=222

My code is wrong, happy about suggestions!

var first = "http://www.google.com?ID=111";
var second = "ID=222";

function searching(){
    var update="";
    if (arguments[0]==/^\w+@\w+\.com$/i){
        return arguments[0]+"?"+arguments[1];
    }
    else {
        update=arguments[0].match(/(\w+@\w+\.com) \?\w+\d/i);
    }
    return update + "?" +arguments[1]; 
}

searching(first, second);
Barmar
  • 741,623
  • 53
  • 500
  • 612
learningcoding
  • 187
  • 2
  • 14

2 Answers2

1

You can't just compare a string to a regex with ==. Basically your choices are match, test, replace, and split. your regex btw has a \w when you wanted just a w, should be: /www\.\w+\.com$/i - I just shortened it even further. there's a million shades of regex validation when it comes to testing for valid URL in javascript. Generally, I think, you should just construct a "good enough" regex for your use case: here we just care if the query param is there, or not:

var first = "http://www.google.com?ID=111";
var second = "ID=222";
function searching(){
    var update="";
    if (/^.*\.com$/i.test(arguments[0])){ 
        //pattern just checks end of string to see if query param is present.
        return arguments[0]+"?"+arguments[1];
    }
    else {
        update=arguments[0].replace(/ID=\d+/, second); //
    }
    return update;
}
searching(first, second);
Community
  • 1
  • 1
Scott Weaver
  • 7,192
  • 2
  • 31
  • 43
0

You could just check for the ? and if the first argument contain the sign '?' then get the first part (url) using .split('?')[0] and add second argument arguments[1], else just add the second argument directely to the first argument (url) :

function searching()
{
    if (arguments[0].indexOf('?')!=-1)
        return arguments[0].split('?')[0]+"?"+arguments[1];
    else 
        return arguments[0]+"?"+arguments[1];
}

Hope this helps.

Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101