最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Use regexp to filter for question mark (?) parameter in url and add either ? or & - Stack Overflow

programmeradmin3浏览0评论

I have this:

var searchString = action +  ?  + 'search=' + search + '&filter='

the action variable could either already have a ?parameter or could not have one.

therefore I need to test action if it already contains a ? and if so append &search. Otherwise I need to use ?search

Any idea how to solve that in an easy manner?

I have this:

var searchString = action +  ?  + 'search=' + search + '&filter='

the action variable could either already have a ?parameter or could not have one.

therefore I need to test action if it already contains a ? and if so append &search. Otherwise I need to use ?search

Any idea how to solve that in an easy manner?

Share Improve this question edited Aug 16, 2011 at 19:14 MaxiWheat 6,2507 gold badges51 silver badges77 bronze badges asked Aug 15, 2011 at 18:26 mattmatt 44.5k107 gold badges268 silver badges402 bronze badges 2
  • to be clear, action can contain the ? character, or can it contain the ? character plus a parameter (more characters) after? – thekaveman Commented Aug 15, 2011 at 18:28
  • it can contain both right! action could look like this something?param&param or something?param or just something therefore I need to find out I append another ? or not because it's not allowed to have two ? – matt Commented Aug 15, 2011 at 18:31
Add a ment  | 

5 Answers 5

Reset to default 4
var searchString = action + (action.indexOf('?') != -1 ? '&' : '?') + 'search=' + search + '&filter=';
var searchString = action + ((action.indexOf('?') == -1) ? '?search=' : '&search=');

Or you can use the jquery Query Plug-in http://plugins.jquery./project/query-object

var startChar = action.indexOf('?') == -1 ? '?' : '&',
    searchString = action +  startChar  + 'search=' + search + '&filter=';

quick, not super readable way:

var hasQM = (/\?/).test(action);
var searchString = action + (!hasQM ? '?' : '&') + 'search=' + search + '&filter='
var string = "?somerandonmestuffhere";
alert((string.match(/[?].*/) || ["?" + string])[0])
var string = "somerandonmestuffhere";
alert((string.match(/[?].*/) || ["?" + string])[0])
发布评论

评论列表(0)

  1. 暂无评论