What is the easiest way to read/manipulate query string params using javascript?

后端 未结 7 1894
余生分开走
余生分开走 2020-12-05 11:45

The examples I\'ve seen online seem much more complex than I expected (manually parsing &/?/= into pairs, using regular expressions, etc). We\'re using asp.net

7条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-05 12:10

    Use the String utility from prototypejs.org, called toQueryParams().

    Example from their site: http://prototypejs.org/api/string/toQueryParams

    'section=blog&id=45'.toQueryParams();
    // -> {section: 'blog', id: '45'}

    'section=blog;id=45'.toQueryParams();
    // -> {section: 'blog', id: '45'}

    'http://www.example.com?section=blog&id=45#comments'.toQueryParams();
    // -> {section: 'blog', id: '45'}

    'section=blog&tag=javascript&tag=prototype&tag=doc'.toQueryParams();
    // -> {section: 'blog', tag: ['javascript', 'prototype', 'doc']}

    'tag=ruby%20on%20rails'.toQueryParams();
    // -> {tag: 'ruby on rails'}

    'id=45&raw'.toQueryParams();
    // -> {id: '45', raw: undefined}

    Also, you may use the alias parseQuery() to obtain the same results.

    window.location.search.parseQuery();
    

    Since window.location returns an object, you must obtain the string.

提交回复
热议问题