简体   繁体   中英

Remove part of attribute value with jquery or javascript

There is a data parameter for a div that looks as follows:

<div data-params="[possibleText&]start=2011-11-01&end=2011-11-30[&possibleText]">
</div>

I want to remove the from the start through the end of the second date from that data-params attribute. There may or may not be text before the start and after the date after the second date.

How can I accomplish this using javascript or jQuery? I know how to get the value of the "data-params" attribute and how to set it, I'm just not sure how to remove just that part from the string.

Thank you!

Note: The dates will not always be the same.

I'd use a regular expression :

var text = $('div').attr('data-params');
var dates = text.match(/start=\d{4}-\d{2}-\d{2}&end=\d{4}-\d{2}-\d{2}/)[0]

// dates => "start=2011-11-01&end=2011-11-30"

The regular expression is not too complex. The notation \\d means "match any digit" and \\d{4} means "match exactly 4 digits". The rest is literal characters. So you can see how it works. Finally, that [0] at the end is because javascript match returns an array where the first element is the whole match and the rest are subgroups. We don't have any subgroups and we do want the whole match, so we just grab the first element, hence [0] .

If you wanted to pull out the actual dates instead of the full query string, you can create subgroups to match by adding parenthesis around the parts you want, like this:

var dates = text.match(/start=(\d{4}-\d{2}-\d{2})&end=(\d{4}-\d{2}-\d{2})/)

// dates[0] => "start=2011-11-01&end=2011-11-30"
// dates[1] => "2011-11-01"
// dates[2] => "2011-11-30"

Here, dates[1] is the start date (the first subgroup based on parenthesis) and dates[2] is the end date (the second subgroup).

My regex skills aren't that good but this should do it

var txt = "[possibleText&]start=2011-11-01&end=2011-11-30[&possibleText]";
var requiredTxt = txt.replace(/^(.*)start=\d{4}-\d{2}-\d{2}&end=\d{4}-\d{2}-\d{2}(.*)$/, "$1$2");

I'm sure there are better ways to match your string with regex, but the $1 and $2 will put the first group and second group match into your requiredTxt stripping out the start/end stuff in the middle.

Say you have your data-params in a variable foo . Call foo.match as follows:

foo.match("[\\?&]start=([^&#]*)"); //returns ["&start=2011-11-01", "2011-11-01"]
foo.match("[\\?&]end=([^&#]*)"); //returns ["&end=2011-11-30", "2011-11-30"]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM