Nishant123 Nishant123 - 8 months ago 39
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 =;
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 type="text/javascript">
var product= GetURLParameter("name");
var producttype=GetURLParameter("type");
var prod = product.replace(/%20/g," ");
var productname = prod.split('\\s+(?=\\d+M[LG])');

My Input String is "
Calpol Plus 200MG

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

The regex I am using is


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