我正在尝试将字符串拆分为数组,但是我正在使用的正则表达式似乎无法正常工作
我的密码
<script type="text/javascript">
function GetURLParameter(sParam)
{
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++)
{
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam)
{
return sParameterName[1];
}
}
}
</script>
<script type="text/javascript">
$(document).ready(function(){
var product= GetURLParameter("name");
var producttype=GetURLParameter("type");
var prod = product.replace(/%20/g," ");
var productname = prod.split('\\s+(?=\\d+M[LG])');
alert(productname[0]);
});
</script>
我的输入字符串是“
Calpol Plus 200MG
”预期输出为
array[0] = "Calpol Plus"
和array[1] = "200MG"
我正在使用的正则表达式是
\\s+(?=\\d+M[LG])
最佳答案
代替
"Calpol Plus 200MG".split('\\s+(?=\\d+M[LG])')
您必须使用以下之一:
RegExp
构造函数,用于将字符串转换为正则表达式:"Calpol Plus 200MG".split(RegExp('\\s+(?=\\d+M[LG])'))
直接使用正则表达式文字:
"Calpol Plus 200MG".split(/\s+(?=\d+M[LG])/)
请注意,在这种情况下,您无需将
\
字符换成另一个\
。