0

I am using delimiter to split one string example:

Test &&Product &Order &number &Test & Final

here delimiter is "&" here i want values as

Test &,Product, Order, number, Test & Final

first value should be "Test &" and last value should be "Test & Final" can anyone help me how to do this.

shitanshu
  • 222
  • 2
  • 6
  • 18
  • Anything you achieved so far? – Norman Apr 25 '16 at 12:06
  • `str = "Test &&Product &Order &number";` `> str.split(/&(?!&)/);` `> ["Test &", "Product ", "Order ", "number"]` as suggested by Alex able to get the first value but not able to create regex for last value – shitanshu Apr 25 '16 at 12:16

1 Answers1

3

Negative lookahead:

> str = "Test &&Product &Order &number";
> str.split(/&(?!&)/);

> ["Test &", "Product ", "Order ", "number"]

From your edit it looks like you are trying to parse a query string, there are better ways to do this than a RegEx but the problem is your query string is broken in that its been incorrectly encoded/decoded - an ampersand cannot appear within a value. If you have access to the raw query string you should parse it correctly.

Alex K.
  • 171,639
  • 30
  • 264
  • 288
  • Thanks @Alex K. it is working in this case but have one more case when String is something like '&orderIDType=PONUMBER&orderIDNumber=Final & Test&customerSoldTo=&customerShipTo=&orderStatus here orderIDNumber' value is complete String "Final & Test" but it is spliting on Final "&" Test please help to create a regex which will work for both. – shitanshu Apr 25 '16 at 11:38
  • yeah actually what i was trying to do to create a url with all the form values and then parsing the url to set the values in form and send ajax query to complete the search process we are doing this to maintain the search results on each page. – shitanshu Apr 25 '16 at 12:11
  • 1
    In your example here, the url should be: "&orderIDNumber=Final%20%26%20Test" - you're not url encoding (`escape` in js) the value *into* the url in the first place. – freedomn-m Apr 25 '16 at 12:29
  • Yes, and when you do that you can read elsewhere with http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript – Alex K. Apr 25 '16 at 12:30