Reputation: 161
I am trying to form a URL by joining different elements. I am getting
TypeError: Cannot read property 'replace' of undefined.
When I am running the following code. Any suggestion is much appreciated!
...
function joinUrlElements() {
"use strict";
var re1 = new RegExp('^\\/|\\/$', 'g'),
elts = Array.prototype.slice.call(arguments);
return elts.map(function (element) {
return element.replace(re1, "");
}).join('/');
}
....
Upvotes: 1
Views: 4956
Reputation: 2049
One of the arguments when you are calling this function causes an element of the array to be "undefined" and when map tries to operate on this item it throws the error.
Upvotes: 0
Reputation: 68645
This means that your elts
has a item, which value is set to undefined
.
Also with ES6
you ca use rest parameters which will replace using arguments
variable in your case.
See an example
function joinUrlElements(...args) {
var re1 = new RegExp('^\\/|\\/$', 'g');
return args.map(function (element) {
return element.replace(re1, "");
}).join('/');
}
console.log(joinUrlElements('first', 'second', 'third'));
Upvotes: 1