Javascript在http://之后添加到字符串?

Javascript在http://之后添加到字符串?,javascript,jquery,Javascript,Jquery,我有一个url,我想把这个url添加到blah.com的前端 这将导致 这在javascript中是可能的吗 问候, var url = "http://blah.com" var new_url = url.replace(/^http:\/\//, "http://something_") /^http:\/\/是一种用于匹配字符串模式的对象类型。这允许我指定(使用^)我只想替换https://,如果它发生在字符串的开头 如果您知道字符串将以“http://”开头,您也可以使用字符串作为替

我有一个url,我想把这个url添加到blah.com的前端

这将导致

这在javascript中是可能的吗

问候,

var url = "http://blah.com"
var new_url = url.replace(/^http:\/\//, "http://something_")
/^http:\/\/
是一种用于匹配字符串模式的对象类型。这允许我指定(使用
^
)我只想替换
https://
,如果它发生在字符串的开头

如果您知道字符串将以“http://”开头,您也可以使用字符串作为替换目标,因为默认情况下只替换第一个匹配项

var new_url = url.replace("http://", "http://something_")
如果您想要与任何协议(HTTP、HTTPS、FTP或其他)一起工作,可以使用正则表达式“捕获”原始字符串的该部分,并在替换中使用它

var new_url = url.replace(/^([a-zA-Z][a-zA-Z0-9\.\+\-]*):\/\//, "$1://something_")
将这种特殊的pattenern一块一块地分解:

  • ^
    必须从字符串开头开始
  • 启动“捕获”组
  • [a-zA-Z]
    匹配任何字母
  • [a-zA-Z0-9\.\+\-]*
    后跟任意字母、数字、句点、加号或连字符,可重复任意次数
  • 结束捕获组
  • :\/\/
    匹配
    “:/”
/^http:\/\/
是一种用于匹配字符串模式的对象类型。这允许我指定(使用
^
)我只想替换
https://
,如果它发生在字符串的开头

如果您知道字符串将以“http://”开头,您也可以使用字符串作为替换目标,因为默认情况下只替换第一个匹配项

var new_url = url.replace("http://", "http://something_")
如果您想要与任何协议(HTTP、HTTPS、FTP或其他)一起工作,可以使用正则表达式“捕获”原始字符串的该部分,并在替换中使用它

var new_url = url.replace(/^([a-zA-Z][a-zA-Z0-9\.\+\-]*):\/\//, "$1://something_")
将这种特殊的pattenern一块一块地分解:

  • ^
    必须从字符串开头开始
  • 启动“捕获”组
  • [a-zA-Z]
    匹配任何字母
  • [a-zA-Z0-9\.\+\-]*
    后跟任意字母、数字、句点、加号或连字符,可重复任意次数
  • 结束捕获组
  • :\/\/
    匹配
    “:/”
使用

使用


这个可以与http或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;

这个可以与http或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;

您不需要jQuery。使用split()


您不需要jQuery。使用split()


你是说像字符串操纵?你是说像字符串操纵?您可能需要编辑此答案:
String
是内置构造函数。:-)您可能需要编辑此答案:
String
是内置构造函数。:-)