Home  >  Article  >  Web Front-end  >  javascipt regular expression to match single-line and multi-line comments_javascript tips

javascipt regular expression to match single-line and multi-line comments_javascript tips

WBOY
WBOYOriginal
2016-05-16 17:13:481883browse

When using node.js. If we use a .json file to store some configurations, we want to add some comments.

However, when reading, the string is read and then JSON.parse is used to convert it into a json object. Due to the existence of comments, it cannot be converted correctly or even an error is reported.

The following regular expression matches all comments in the string, including single-line and multi-line comments

Copy code The code is as follows:

(/*([^*]|[rn]|(* ([^*/]|[rn])))** /)|(//.* )

Test address:
http://gskinner.com/RegExr/?30jrh
Note that when using it as a regular string, be careful to use escape characters

So you need to write the following:
Copy code The code is as follows:

var reg = "(/\*([^*]|[\r\n]|(\* ([^*/]|[\r\n])))*\* /)|(//.*) ";
var exp = new RegExp(reg,"g");

is represented by \
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn