[英]Split string using split() method
I am trying to split a string into array but the regex I am using doesn't seem to work 我正在尝试将字符串拆分为数组,但是我正在使用的正则表达式似乎不起作用
My code 我的密码
<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>
My Input String is " Calpol Plus 200MG
" 我的输入字符串是“
Calpol Plus 200MG
”
Expected output is array[0] = "Calpol Plus"
and array[1] = "200MG"
预期输出为
array[0] = "Calpol Plus"
和array[1] = "200MG"
The regex I am using is \\\\s+(?=\\\\d+M[LG])
我正在使用的正则表达式是
\\\\s+(?=\\\\d+M[LG])
You passed your regex as a string, see? 您以字符串形式传递了正则表达式,明白吗?
var productname = prod.split('\\s+(?=\\d+M[LG])');
You need to pass it as a regex literal: 您需要将其作为正则表达式文字传递:
var productname = prod.split(/\\s+(?=\\d+M[LG])/);
split()
will split either by a regex, or by a substring, depending on what is passed. split()
将根据正则表达式或子字符串进行拆分,具体取决于传递的内容。
Instead of 代替
"Calpol Plus 200MG".split('\\s+(?=\\d+M[LG])')
You must use one of these: 您必须使用以下之一:
RegExp
constructor to convert your string to a regular expression: RegExp
构造函数,用于将字符串转换为正则表达式:
"Calpol Plus 200MG".split(RegExp('\\\\s+(?=\\\\d+M[LG])'))
Directly use a regular expression literal: 直接使用正则表达式文字:
"Calpol Plus 200MG".split(/\\s+(?=\\d+M[LG])/)
Note in this case you don't need to scape the \\
characters with another \\
. 请注意,在这种情况下,您不需要将
\\
字符换成另一个\\
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.