[JavaScript] Please help me understand this code. via /r/learnprogramming


[JavaScript] Please help me understand this code.

var name = "dea+hl[]rd"; var text = "This dea+hl[]rd guy is super annoying."; var escaped = name.replace(/[^\w\s]/g, "\\$&"); var regexp = new RegExp("\\b(" + escaped + ")\\b", "gi"); console.log(text.replace(regexp, "_$1_")); // → This _dea+hl[]rd_ guy is super annoying. 
  1. I've played around with the var escape, and I noticed that the outcome is still the same when I remove \s. Why is that? If this is the case, why do we need both?

  2. When I console.log(escaped), it results in dea\+hl\[\]rd. How did this happen from \$&?

  3. I am completely unable to understand var regexp.

I thank you for taking your time to read this.

I appreciate all help provided.

Submitted July 15, 2017 at 06:10PM by NewbiusCoder
via reddit http://ift.tt/2uvJbVc

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s