Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use javascript regular implementation to remove comments

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces the knowledge of "how to use javascript regular implementation to remove comments". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

1 single-line comment

A single-line comment either occupies an entire line or is in the * * of a line.

Under normal circumstances, it is not difficult, directly through regular matching, and then remove it with the replace method.

Let codes = `let name = "Wmaker"; / / This is name. If (name) {/ / Print name. Console.log ("His name is:", name);} `; console.log (codes.replace (/\ /\ /. * $/ mg,''); / / print out: / / let name = "Wmaker"; / / if (name) {/ console.log ("His name is:", name); / /}

The comments above are successfully deleted, but the comments that occupy an entire line are not cleaned thoroughly enough, leaving blank lines. In fact, the space in front of the end-of-line comment is also preserved. So the goal is slightly higher to clear these gaps. It is not difficult to operate, and the idea goes something like this: to delete the entire line is actually to delete the newline character at the end of the line or the newline character at the end of the previous line. The newline character itself is also a blank character. So all you have to do is manipulate the regular, match the comment and all the spaces in front of the comment, and kill two birds with one stone.

Let codes = `let name = "Wmaker"; / / This is name. If (name) {/ / Print name. Console.log ("His name is:", name);} `; console.log (codes.replace (/\ s*\ /. * $/ mg,''); / / print out: / / let name = "Wmaker"; / / if (name) {/ / console.log ("His name is:", name); / /}

If the full URL address appears in the string, the above regular will directly match and delete it. On the Internet, most of the URL format features (http://xxx): double underscores preceded by colons are used as a solution. But this is only a palliative approach, after all / / it is free to appear in a string in any form, and we have no way to interfere.

The question then turns to: how do you make a regular match exist in double underscores outside quotation marks?

Code blocks with double underscores are relatively simple to match in quotation marks: / ". *\ /. *" / mg. The difficulty is how to achieve this negation, that is, when the regular match is double underlined, and then determine whether it is in quotation marks? I racked my brains and checked a lot on the Internet, but there were no decent results. Calm down, wash your face and brush your teeth, and then rinse your head to calm down. I feel that it is impossible to simply use the regular road, so I have to jump out of this circle.

Just at the moment, there was a sudden radiance above the obscene and filthy room. I hurriedly covered my bloodshot eyes and waited for them to adapt. There appeared a paragraph of text (Chinese): son, just replace the string with / / surrounded by quotation marks, remove the comment and then restore it, won't you?

Let codes = `let name = "Wmaker"; / / This is name. If (name) {/ / Print name. Console.log ("His name is:", name); console.log ("Unusual situation, characters of / / in quotation marks.");} `; / / the previous method. Console.log (codes.replace (/\ s *\ /. * $/ mg,''); / / print out: / / let name = "Wmaker"; / / if (name) {/ / console.log ("His name is:", name); / / console.log ("Unusual situation, characters of / /} / / the current way. Console.log (removeComments (codes)); / / print out: / / let name = "Wmaker"; / / if (name) {/ / console.log ("His name is:", name); / / console.log ("Unusual situation, characters of / / in quotation marks."); / /} function removeComments (codes) {let {replacedCodes, matchedObj} = replaceQuotationMarksWithForwardSlash (codes) ReplacedCodes = replacedCodes.replace (/\ s *\ /. * $/ mg,''); Object.keys (matchedObj) .forEach (k = > {replacedCodes = replacedCodes.replace (k, matchedObj [k]);}); return replacedCodes; function replaceQuotationMarksWithForwardSlash (codes) {let matchedObj = {}; let replacedCodes =''; let regQuotation = / ". *\ /. *" / mg Let uniqueStr = 'QUOTATIONMARKS' + Math.floor (Math.random () * 10000); let index = 0; replacedCodes = codes.replace (regQuotation, function (match) {let s = uniqueStr + (index++); matchedObj [s] = match; return s;}); return {replacedCodes, matchedObj};}}

Yes, the goal has been achieved. God is blessed!

In addition, there is one area that needs to be optimized: there are three ways to define strings, and so far we have only matched double quotes.

In order to avoid regular memory function, regular literals are used for testing.

-before.

Console.log (/ ". *\ /\ /. *" / mg.test (`'Unu//sual'`); / / false console.log (/ ". *\ /. *" / mg.test (`"Unu//sual"`); / / true console.log (/ ". *\ /. *" / mg.test (`\ `Unu//sual\ ``)); / / false

-after that

Console.log (/ ('| "| `). *\ /. *\ 1/mg.test (` 'Unu//sual' `); / / true console.log (/' |" |`). *\ /. *\ 1/mg.test (`"Unu//sual"`)); / / true console.log (/ ('| "| `). * /\ / .*\ 1/mg.test (`\ `Unu//sual\ ``)); / / true

Aah! That's the end of the problem!

Is it really over? No, no! I looked at the time: 02:17, then took off my glasses, pulled a tissue and wiped away a few tears.

Here are two problems solved in succession: greedy mode and escape characters.

-STEP 1, caused by regular greed patterns. Let codes = `let str = 'abc//abc'; / / abc' `; console.log (codes.match (/ (' | "|`). * /\ /. *\ 1/mg)); / / [" 'abc//abc'; / / abc' "]-- solve let codes = `let str =' abc//abc'; / / abc' ` Console.log (codes.match (/'| "| `). *?\ /\ /. *?\ 1/mg); / / [" 'abc//abc' "]-STEP 2, caused by the escape characters in the string definition. Let codes = `let str = 'http://x\\'x.com'; / /' acs `; console.log (codes.match (/ ('| "|`). *?\ /\ /. *?\ 1/mg)); / / [" 'http://x\'", "'; / /'"]-solve let reg = / (?

At this point, although tired, but more or less a sense of achievement, after all, a success.

However, during the test, I inadvertently found an insurmountable obstacle. Just like after painstaking efforts and endless financial and material resources, so-and-so is finally willing to go to Lovers Point Inn, only to find that every house is full and there is no spare room. Pretending to laugh, playing with her life, a family after another looking for until finally booked to the room, but found that they can not stand up!

The regular will take the quotation marks anywhere as the starting position of the search, and it doesn't care if the quotation marks are in pairs. Here is an example.

Let reg = / (? {replacedCodes = replacedCodes.replace (k, matchedObj [k]); return replacedCodes; function replaceQuotationMarksWithForwardSlash (codes) {let matchedObj = {}; let replacedCodes =''; let regQuotation = / (? this is the end of the article on how to use javascript regular implementation to remove comments. Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report