Basque0407 Basque0407 - 3 months ago 31
Javascript Question

Javascript - Calling Hash values through regex derived keys

I have the code as follows:

var str =
<a href="#h-1">
<a href="#h-2">
<a href="#h-3">
<a href="#h-9">

var veg_anchor_map = new Object();
veg_anchor_map['h-1'] = 'cabbage';
veg_anchor_map['h-2'] = 'potato';
veg_anchor_map['h-3'] = 'carrot';

var href_regex = /<a href="#(.*?)"/g;
str = str.replace(href_regex, veg_anchor_map['$1']);

I'm trying to replace all href links in my str variable to this syntax:


but every time I try to call the call the groupings in my regex statement it states, that it's undefined, can anybody help me with this? Thank you.


Use String.replace() function with callback function as a second argument:

var href_regex = /<a href="#(.*?)"/g;
str = str.replace(href_regex, function ($m0, $m1) {
    return veg_anchor_map[$m1] || $m0;
console.log(str); // <doc>cabbage>potato>carrot></doc><doc><a href="#h-9"></doc>
  • veg_anchor_map[$m1] || $m0 will return a replacement value from the veg_anchor_map object, otherwise(if not found) - returns the current match string