Removing #hash comments from a string using regEx in JavaScript

Last night i was looking for a method to remove comments from a robots.txt file containing contents of form below

`# robots.txt

Or a more practical format obtained by splitting the robots.txt file line by line.

["# robots.txt",

every element of the array is a string representing a single line of text from a robots.txt plain text file.

Regular expression
I used regular expression to strip out the unwanted text until the end of the line
however it's not limited to robots.txt it works perfectly with files as well.

var string = "Disallow / #deny bots"
string.replace(/#.*$/, "")
// returns  Disallow /

It simply strip's off all characters after the hash character until the end of the line.


Popular posts from this blog

How to get user's ip address in JavaScript

How to make a static http server in nodejs using express

Array concat method in JavaScript

What is 'this.' keyword in JavaScript

How to create promises in JavaScript