简体   繁体   中英

String.replace() with regular expression

I'm having difficulty getting String.replace() to work with JavaScript. It returns in console TypeError: url is undefined

var url = $(this).attr("href");
var id  = url.replace(/(^.{4})(&remove=1)/, "");
console.log(id);

The jquery statement $(this).attr("href") is returning undefined.

Thats why it says url is undefined.

If your error is TypeError: url is undefined, it means that "$(this).attr("href");" returns undefined. Your regular expression is ok.

Try outputin the content of this, $(this) and $(this).attr("href"). You'll see where the problem is (your whole selector may be broken, or you may select an element that just does not have the "href" attribute).

It appears that either this is not a DOM object or if it is a DOM object, then it doesn't have an href attribute. Here's the logic and simple test app that leads to that conclusion.

Your error means that url is undefined. Since url is the product of $(this).attr("href") , we have to figure out how that expression can be undefined.

As long as you have jQuery installed, then $(this) can't be undefined and if it was, you'be getting a different error about referencing the .attr() method. So, we can assume that $(this) must be a valid jQuery object.

So, it appears that you either have an empty jQuery object or that the this element does not have an href attribute.

Running a quick jsFiddle test shows that either condition will result in url being undefined. So, you have to figure out whether this is not a DOM object or whether your DOM object doesn't' have the href attribute. It's one of those two causes.

Here's the test code:

// all  of these tests print "undefined" to the console

// a DOM object that doesn't have the href attribute because
// #test is just an ordinary div
var url = $("#test").attr("href");
console.log(url);

// an empty jQuery object because #foo doesn't exist
url = $("#foo").attr("href");
console.log(url);

// a non DOM object in the jQuery object
url = $({}).attr("href");
console.log(url);

You can debug this more yourself by doing this:

console.log("begin marker");
console.log(this);
console.log(this.href);
var url = $(this).attr("href")
console.log(url);
console.log("end marker");

And, then report back what those console.log() statements show.

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