JavaScript:从useragent的一部分创建变量

时间:2018-05-16 12:21:09

标签: javascript regex replace

因此,我在运行Sitekiosk的商店中设有自助服务终端,在这些自助服务终端上,我将appragent utm_source添加到页面中的网址,以便在Google Analytics中进行跟踪。我们有sitekiosk在useragent中广播机器的名称,例如

utm_source=Mozilla/5.0%20(Windows%20NT%206.1;%20WOW64;%20Trident/7.0;%20rv:11.0;%20SiteKiosk%209.5%20Build%204117;%20MACHINE10%20shopkiosk)

MACHINE10是商店中信息亭的标识符。

使用这个完整的useragent附加到网址很容易。我从useragent创建了一个变量并将其添加到url:

var machine=navigator.userAgent;

这样的长utm_source在谷歌分析中不易读取(并且会弄乱我的报告),所以我正在寻找一种不追加完全使用者的方法,而只是寻找{{1部分。

有没有办法只在变量中使用useragent的那部分?这里的一个问题是并非所有机器的名称都有2位数,有些有3位数。其余的使用者对所有机器都是一样的。

1 个答案:

答案 0 :(得分:0)

用于获取机器编号的正则表达式:

//Looks through the string until it finds the word MACHINE, then captures
//any amount of digits up to hitting the percentage sign
const regEx = /.*?MACHINE(\d+)%.*?/;
//Grab the capture groups
const captures = regEx.exec(navigator.userAgent);
//Set the last capture group value to variable which is the machine #
const machineNum = captures[captures.length - 1];