简体   繁体   中英

Javascript add to string after http://?

I have a url http://blah.com and I want to take the url and add something to the front of the blah.com

Which would result in http://something_blah.com

Is this possible with javascript?

Regards,

var url = "http://blah.com"
var new_url = url.replace(/^http:\/\//, "http://something_")

/^http:\\/\\// is a regular expression , a type of object used to match patterns of strings. This allows me to specify (using ^ ) that I only want to replace https:// if it occurs at the start of the string.

If you know the string is going to start with "http://", you could also just use a string as the replacement target because .replace() only replaces the first match by default.

var new_url = url.replace("http://", "http://something_")

If you want something that will work with any protocol, HTTP, HTTPS, FTP or whatever, you can use a regular expression that "captures" that part of the original string and uses it in the replacement.

var new_url = url.replace(/^([a-zA-Z][a-zA-Z0-9\.\+\-]*):\/\//, "$1://something_")

Breaking this particular pattenern down piece by piece:

  • ^ it must begin at the start of the string
  • ( start a "capturing" group
  • [a-zA-Z] match any letters
  • [a-zA-Z0-9\\.\\+\\-]* followed by any letters, digits, periods, plusses or hyphens, repeated any number of times.
  • ) end the capturing group
  • :\\/\\/ match "://"

Use Javacript Replace

myString = "http://blah.com";
myString.replace("http://", "http://something_");

This one works with http or https

    var url = window.location.href;
    var i = url.indexOf ('://') + 3;
    var newUrl = url.substring(0, i) + 'something_' + url.substring (i, url.length);
    window.location.href = newUrl;

You don't need jQuery. Use split().

var text = 'something_';
var a = "http://blah.com";
var b = a.split("http://")[1];
var c = "http://"+text+b;
alert(c);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM