Reputation: 169
I have the following script:
$(".balkenclosed").click(function() {
window.location = $(this).find("a").attr("href");
return false;
});
I try to add a .replace function like this:
var replace = new Map([
/ [^a-zA-Z0-9\s]/ig, "", $id
]),
id = a;
replace.forEach(function(value, key){
id = id.replace(key, value);
});
It should replace invalid characters in the id of divs like this one:
<div class="balken"><div class="balkenopen"><a id="2our$ / team/2$"
style="text-decoration:none; color:black;" href="#2our$ / team/2$">
our team</a></div></div>
The result in this case should be id:"our_team" and href:"our_team"
My approach doesn't work and I feel like I'm completely wrong. I would really appreciate any hint into the right direction
Upvotes: 1
Views: 78
Reputation: 1497
I have written jquery, which will produce your desired result, you can refine though. Hope this will help you.
Please consider that it will search for entire anchor tag and replace if matches found. Replace
$(a)
with the more appropriate selector for the specific search.
$('a').each(function() {
var self = $(this);
var id = self.attr('id');
var href = self.attr('href');
if (id)
self.attr('id', stripEverything(id, '_'));
if (href)
self.attr('href', '#'+stripEverything(href, '_'));
});
function stripEverything(string, replaceSpaceWith) {
return string.replace(/[^a-zA-Z ]+/g, '').split(' ').filter(function(e) {
return e
}).join(replaceSpaceWith);
}
You can look the solution at Fiddle
Upvotes: 1
Reputation: 68413
Use value
as the regex
var replace = [
/[^a-zA-Z0-9\s]/ig, ""
];
replace.forEach(function(value, key){
id = id.replace( value, "");
});
In fact, looking at the content of replace, simply
id = id.replace( replace[0], replace[1]);
Upvotes: 1