SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Zealot
    Join Date
    May 2004
    Location
    London
    Posts
    155
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Search and replace in javascript

    Hi

    Could some help me with a javascript search and replace function....

    var mylink = "mens-shirts.new-arrivals";

    I just need to able to replace what comes after the "." with something else. eg. I want to end up with mylink being "mens-shirts.price-high-low" or "mens-shirts.-a-z and so on.

    So just a generic function where I can input the new value each time.

    Thanks very much

  2. #2
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    5,892
    Mentioned
    211 Post(s)
    Tagged
    12 Thread(s)
    Hi there,

    use JavaScript's replace() function with a regular expression.
    For example:
    Code JavaScript:
    var mylink = "mens-shirts.new-arrivals";
    var newlink = mylink.replace(/\..*$/,".price-high-low");
    alert(newlink);

    Alternatively, you could abstract this into a function.
    E.g.
    Code JavaScript:
    function myReplace(str, rep){
      return(str.replace(/\..*$/, "." + rep));
    }
    var mylink = "mens-shirts.new-arrivals";
    var newlink = myReplace(mylink, "price-high-low");
    alert(newlink);


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •