【发布时间】:2012-09-26 16:21:45
【问题描述】:
我正在尝试删除可能出现在我的 Google Analytics 标记中的特殊字符,因为这些特殊字符似乎会在某些版本的 IE 中导致脚本错误。我有这个功能:
function removeSplChars(inStr) {
inStr = inStr.replace(/[^a-zA-Z0-9 ]/g, "");
return inStr;
}
并且有当前有效的 GA 代码:
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', '<c:out value="${profileId}"/>']);
<c:choose>
<c:when test="${(lastCmdName eq 'CategoryDisplay') or (lastCmdName eq 'ProductDisplay')}" >
_gaq.push(['_setCustomVar',
2, // This custom var is set to slot #2.
'<c:choose><c:when test="${WCParam.source eq 'search'}">Search</c:when><c:otherwise><c:out value="${topCat}" /></c:otherwise></c:choose>', // The top-level name for your online content categories.
'<c:choose><c:when test="${WCParam.source eq 'search'}">Search <c:out value="${WCParam.searchTerm}" /></c:when><c:otherwise><c:out value="${topCat}" />|<c:out value="${subCatA}" />|<c:out value="${subCatB}" />|<c:out value="${subCatC}" /></c:otherwise></c:choose>', // Records value of breadcrumb name
3 // Sets the scope to page-level.
]);
</c:when>
<c:otherwise>
</c:otherwise>
</c:choose>
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
但是当我将该函数放在代码中时,我仍然看到 Chrome 调试器中出现了特殊字符。例如,当我打开一个包含名为“Matt's”的产品的页面时,它会显示为 Matt's。我想要的是马茨。我们还有其他带有 & 和其他特殊字符的产品名称,所以我只想允许 A-z 和数字(大写/没有大写都可以)
任何建议将不胜感激。我查看了关于 SO 的以下帖子,但到目前为止还没有发现任何可以帮助我完成这项工作的内容:
How to handle (® ´ © ¿ ¡ ° À ) special characters in javascript?
javascript regexp remove all special characters
Remove all special characters except space from a string using JavaScript
我是 JSP 和 JavaScript 的新手,所以我确定我没有将代码放在正确的位置,或者我可能需要在页面上添加其他内容?我尝试将 removeSplChars 函数放在 () 中或添加一个 ;没有运气。不幸的是,我必须在工作中学习这一点,所以我必须专注于完成我被赋予的任务,而不是花时间真正理解语言的逻辑/语法。
【问题讨论】:
-
向我们显示您呼叫
removeSplChars的代码。 -
你可以用三元表达式替换你的内联
c:choose块。示例:${WCParam.source eq 'search' ? 'Search' : 'topCat'} -
@some,这就是整个问题,我不会在任何地方调用它。我是 JavaScript 的菜鸟 :( 我会研究如何调用一个函数,看看我能找到什么。谢谢。
-
@JasperdeVries 如果输入的“topCat”值例如是“Patio & Outdoors”,会有帮助吗?我也会研究三元表达式。
-
对不起,我打错了。
topCat是一个变量,所以你可以使用${WCParam.source eq 'search' ? 'Search' : topCat}
标签: javascript jsp special-characters analytics