String.replace and /

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Ed Brandmark

    String.replace and /

    I am trying to replace the /'s in an URL with %2F
    So if the URL was
    Discover the latest breaking news in the U.S. and around the world — politics, weather, entertainment, lifestyle, finance, sports and much more.

    I want it to be
    http:%2F%2Fwww. netscape.com%2F sports%2F

    To do this I am trying the following JavaScript

    str="http://www.netscape.co m/sports/"
    replaceStr="%2F "

    regExp = /\//g

    str2=str.replac e(regExp, replaceStr)

    and it doesn't work.
    If I replace, say the http - it works fine - so there is something
    wrong with the regular Expression.

    I have also tried:

    delim = "/g"
    regExpValue = "\/"
    regExp = eval ("/" + regExpValue + delim)

    and that didn't work either.

    I receive no errors - but nothing is replaced.

    I did get the following to replace just the first /

    str2=str.replac e("\/", "%2F")

    but would liek to replace all the /'s
  • Chris Crandell

    #2
    Re: String.replace and /


    Ed Brandmark <ebrandmark@aol .com> wrote in message
    news:5fbc4660.0 402241320.2e350 33a@posting.goo gle.com...[color=blue]
    > I am trying to replace the /'s in an URL with %2F
    > So if the URL was
    > http://www.netscape.com/sports/
    > I want it to be
    > http:%2F%2Fwww. netscape.com%2F sports%2F
    >
    > To do this I am trying the following JavaScript
    >
    > str="http://www.netscape.co m/sports/"
    > replaceStr="%2F "
    >
    > regExp = /\//g
    >
    > str2=str.replac e(regExp, replaceStr)
    >
    > and it doesn't work.
    > If I replace, say the http - it works fine - so there is something
    > wrong with the regular Expression.
    >
    > I have also tried:
    >
    > delim = "/g"
    > regExpValue = "\/"
    > regExp = eval ("/" + regExpValue + delim)
    >
    > and that didn't work either.
    >
    > I receive no errors - but nothing is replaced.
    >
    > I did get the following to replace just the first /
    >
    > str2=str.replac e("\/", "%2F")
    >
    > but would liek to replace all the /'s[/color]

    Hi Ed,
    consider the following examples:

    str="http://www.netscape.co m/sports/"
    replaceStr="%2F "

    regExp = new RegExp( "\/", "g");
    alert( regExp);
    str1=str.replac e(regExp, replaceStr)
    alert( str + "\n" + str1);

    str2=str.replac e( /\//g, replaceStr);
    alert( str + "\n" + str2);


    Comment

    Working...