Nishant123
Nishant123

Reputation: 1966

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])

Upvotes: 0

Views: 226

Answers (2)

Oriol
Oriol

Reputation: 288260

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

Upvotes: 2

Scimonster
Scimonster

Reputation: 33409

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.

Upvotes: 3

Related Questions