0

I have the following string and I'm trying to retrieve the string between two symbols

http://mytestdomain.com/temp-param-page-2/?wpv_paged_preload_reach=1&wpv_view_count=1&wpv_post_id=720960&wpv_post_search&wpv-women-clothing[]=coats

I need to retrieve wpv-women-clothing[] or any other string between the last & and the last = in the URL

Should I use regex for this or is there a function in Javascript/jQuery already well suited for this?

Thanks

user2028856
  • 3,063
  • 8
  • 44
  • 71
  • I tend to use [`.split`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split) for this. But regex masters will help you. – loveNoHate Sep 04 '14 at 15:25
  • I'm really new to complex string manipulations, can you offer some tips on how I might achieve this? – user2028856 Sep 04 '14 at 15:26
  • you dont need regex, this is a url, it is assumed that there will be no characters in between that match to '&' ot '='. http://stackoverflow.com/questions/19491336/get-url-parameter-jquery – DarthCoder Sep 04 '14 at 15:27
  • Try this: var str= 'http://mytestdomain.com/temp-param-page-2/?wpv_paged_preload_reach=1&wpv_view_count=1&wpv_post_id=720960&wpv_post_search&wpv-women-clothing[]=coats'; var regex = new RegExp(/&\w*=/g); str.match(regex); – Manjar Sep 04 '14 at 15:35

4 Answers4

3
var str = "http://mytestdomain.com/temp-param-page-2/?wpv_paged_preload_reach=1&wpv_view_count=1&wpv_post_id=720960&wpv_post_search&wpv-women-clothing[]=coats";
var last =str.split('&').pop().split('=')
console.log(last[0]) // wpv-women-clothing[] 

jsFiddle example

Split the string on the ampersands (.split('&')), take the last one (.pop()), then split again on the = (.split('=')) and use the first result last[0].

j08691
  • 204,283
  • 31
  • 260
  • 272
  • Not gonna add an other answer since it's similar, but alternatively, you could do that : `str.split(/[&=]/).splice(-2,1);` – Karl-André Gagnon Sep 04 '14 at 15:29
  • 1
    @Karl-AndréGagnon Awesome. Did not know you can use a `regular expression` for the selector. Learned something. This comment is the best from both worlds. – loveNoHate Sep 04 '14 at 15:40
0

Group index 1 contains your desired output,

\&([^=]*)(?==[^&=]*$)

DEMO

> var re = /\&([^=]*)(?==[^&=]*$)/g;
undefined
> while ((m = re.exec(str)) != null) {
... console.log(m[1]);
... }
wpv_post_search&wpv-women-clothing[]
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
0
.*&(.*?)=.*

This should do it.

See demo.

http://regex101.com/r/lZ5bT3/1

vks
  • 67,027
  • 10
  • 91
  • 124
-1

Can you try:

var String = "some text";
String = $("<div />").html(String).text();

$("#TheDiv").append(String);
idmean
  • 14,540
  • 9
  • 54
  • 83
igrice
  • 1
  • 1