首页 > 解决方案 > 混淆除白名单之外的所有查询参数

问题描述

我正在设置一个跟踪脚本,试图获取不太多的个人数据。我不想存储除少数之外的所有参数的值。

假设我们有这个变量来自window.location.search

var search = '?utm_source=telegram&rel=twitter&password=nooooooo&utm_medium=phone';

我确实尝试了几个小时的正则表达式,但我无法让它工作:

search.replace(/([?&][^=|^(utm_)]+=)[^&#]*/gi, '$1***')

// ?utm_source=telegram&rel=***&password=***&utm_medium=phone

但我很想得到这个输出:

?utm_source=telegram&rel=twitter&password=***&utm_medium=phone

所以它应该替换所有参数的值,***除了以utm_或开头的参数rel

标签: javascriptregex

解决方案


你可以试试这个:

\b((?!rel|utm_)\w+)=[^&]+(?=&|$)

替换为:$1=***

演示

解释:

\b                  # Word boundary
((?!rel|utm_)\w+)   # A word that does not start with rel or utm_
=                   # literal =
[^&]+               # Any non & character repeated 1 or more.
                    # That will match the value
(?=&|$)             # Followed by & or end of line/string

推荐阅读