在http://之后将Javascript添加到字符串? [英] Javascript add to string after http://?
问题描述
我有一个网址 http://blah.com ,我想获取该网址并在其前面添加一些内容blah.com的
I have a url http://blah.com and I want to take the url and add something to the front of the blah.com
这将导致 http://something_blah.com
使用JavaScript可以吗?
Is this possible with javascript?
此致
推荐答案
var url = "http://blah.com"
var new_url = url.replace(/^http:\/\//, "http://something_")
/^http:\/\//
是正则表达式,是一种对象用于匹配字符串模式.这使我可以指定(使用^
)仅在字符串的开头出现时替换https://
.
/^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.
如果您知道字符串以"http://"开头,则也可以使用字符串作为替换目标,因为
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_")
如果您希望某些东西可以与任何协议,HTTP,HTTPS,FTP或其他任何协议一起使用,则可以使用正则表达式来捕获"原始字符串的该部分并在替换中使用它.
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:
-
^
它必须从字符串的开头开始 -
(
启动捕获"组 -
[a-zA-Z]
匹配任何字母 -
[a-zA-Z0-9\.\+\-]*
,后跟任意字母,数字,点,加号或连字符,重复任意次. -
)
结束捕获组 -
:\/\/
匹配"://"
^
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"://"
这篇关于在http://之后将Javascript添加到字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!