Question

I want to use javascript to find part of this link with lots of parameters:

<a class="" data-method="post" href="/daily_drills?commonality%5B%5D=category&amp;commonality%5B%5D=2&amp;daily_drill%5Bgroup_id%5D=2&amp;drill_ids%5B%5D=7&amp;drill_ids%5B%5D=4&amp;drill_ids%5B%5D=3&amp;group=2" id="done-button" rel="nofollow">Done</a>

And add / remove numbers to / from the parameter drill_ids

In the above example, the drill_ids param contains ["7", "4", "3"]:

drill_ids%5B%5D=7&amp;drill_ids%5B%5D=4&amp;drill_ids%5B%5D=3

I have a method that fires when a user clicks a number on the page, if they click "7" I want to remove "7" from the drill_ids params. If they click a number that's not present in the params, I want to append it to the drill_ids params.

  • Since I could render this link as a partial I was thinking of re-rendering the entire thing with the appended drill_ids param, but that would not have an instantaneous response time on a weaker connection.

  • I -could- just go in regex style and add/remove drill_ids%5B%5D=7& (for the number 7), but it seems like there'd be a cleaner way of doing this.

Any tips for how I should approach this?

Was it helpful?

Solution

I ended up doing a simple javascript match as I could not come up with a clever clean solution:

// I build up a string that I want to replace the old string with

// create a list of the ids that I wanted to append
listOfIds = ""
arrayOfIds.forEach (id) ->
  listOfIds = listOfIds+id

// grab the old link in it's entirety
oldLink = $("#done-button").attr("href")
console.log(oldLink)

// grab the string from the old link I don't want
match = oldLink.match(/(?:group_id%5D=2)(.*)(?=&group=)/)[1]

// replace the old string with the new string
newLink = oldLink.replace(match, listOfIds)

// changed the href attribute on the link
$("#done-button").attr('href', newLink)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top