Nishant123 Nishant123 - 5 months ago 15
Javascript Question

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
"

Expected output is
array[0] = "Calpol Plus"
and
array[1] = "200MG"


The regex I am using is
\\s+(?=\\d+M[LG])

Answer

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:

    "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 \.

Comments