I have written a function in Google Tag Manager, where I get the last segment of the url (http://www.testsite.com/amazon:32/) which works great. Seeing the example code below displays "amazon:32", however now I only want to just display "amazon" and store "32" elsewhere. How can I modify the function below to do this?
我在Google跟踪代码管理器中编写了一个函数,在那里我得到了网址的最后一部分(http://www.testsite.com/amazon:32/)。看到下面的示例代码显示“amazon:32”,但是现在我只想显示“amazon”并在其他地方存储“32”。如何修改以下功能才能执行此操作?
<script>
function lastSegment() {
var clickurl = "http://www.testsite.com/amazon:32/";
var brandName = clickurl.match(/\/([^\/]+)[\/]?$/);
brandName[1] = brandName[1].charAt(0).toUpperCase() + brandName[1].slice(1); //capitalize first lett of brand name
alert (lastSegment[1]);
}
</script>
Thanks again for any help!
再次感谢任何帮助!
1 个解决方案
#1
1
You should avoid firing a Regexp just for that. Basically, you should just use url.lastIndexOf('/')
in your case, it's way more efficient and readable.
你应该避免为此发射Regexp。基本上,你应该在你的情况下使用url.lastIndexOf('/'),它更有效和可读。
function getBrandName(url) {
if (url.endsWith('/')) {
url = url.slice(0, url.length - 1);
}
var slashIndex = url.lastIndexOf('/');
if (slashIndex === -1) { return {}; }
var [ brand, number ] = url.slice(slashIndex + 1).split(':');
brand = brand[0].toUpperCase() + brand.slice(1);
return { brand, number };
}
Here is the output when used with your url:
以下是与您的网址一起使用时的输出:
> getBrandName("http://www.testsite.com/amazon:32/")
{ brand: 'amazon', number: '32' }
#1
1
You should avoid firing a Regexp just for that. Basically, you should just use url.lastIndexOf('/')
in your case, it's way more efficient and readable.
你应该避免为此发射Regexp。基本上,你应该在你的情况下使用url.lastIndexOf('/'),它更有效和可读。
function getBrandName(url) {
if (url.endsWith('/')) {
url = url.slice(0, url.length - 1);
}
var slashIndex = url.lastIndexOf('/');
if (slashIndex === -1) { return {}; }
var [ brand, number ] = url.slice(slashIndex + 1).split(':');
brand = brand[0].toUpperCase() + brand.slice(1);
return { brand, number };
}
Here is the output when used with your url:
以下是与您的网址一起使用时的输出:
> getBrandName("http://www.testsite.com/amazon:32/")
{ brand: 'amazon', number: '32' }