开发者

javascript: if first 2 chars are //, replace it with /

开发者 https://www.devze.com 2023-03-20 12:50 出处:网络
I think I may need a regex for this, but since I suck at regexs was hoping someone here could spare a minute to help me.

I think I may need a regex for this, but since I suck at regexs was hoping someone here could spare a minute to help me.

开发者_开发问答

Basically I have a variable (lets name it: zippy)

and if zippy's value is //blah.html

I want to delete one slash from there so it becomes /blah.html

(the 2 slashes will ALWAYS be in the first two characters, IF they exist at all)

How do I do this?

Thanks!


Regex would work, so would

zippy = (zippy.substr(0,2)=="//"  ? zippy.substr(1) : zippy);


zippy = zippy.replace('//', '/');


Can't be simplier:

zippy=zippy.replace('^/{2}','/');

Also +1 for variable names.


if(zippy.substring(0,2) == '//')
{
zippy = '/' + zippy.substring(2);
}

I'm under the impression that substring(from,to) has from inclusive and to exclusive. But something to that effect. I don't know if javascript has a startsWith method.

Edit: Oh if the slashes will always be at the beginning than go with replace.


var zippy = "//blah.html"
var zippy_fixed = zippy.replace(/^\/\//, "/")


Another;

zippy = zippy.substr(1 + zippy.indexOf("//"));
0

精彩评论

暂无评论...
验证码 换一张
取 消