Reputation: 385
I am trying to create a regex that I can use to remove any closing comment syntax out of string.
For instance if I had:
/* help::this is my comment */
should return this is my comment
or <!-- help:: this is my other comment -->
should return this is my other comment
. Ideally I would like to target all major programming languages that require ending comment tags.
Here is what I have so far:
function RemoveEndingTags(comment){
return comment.split('help::')[1].replace("*/", "").replace("-->", ""); //my ugly solution
}
An HTML markup example would be:
<!-- help:: This is a comment -->
<div>Hello World</div>
so the string would be help:: This is a comment -->
Upvotes: 8
Views: 268
Reputation: 14361
This should support many languages including bash which doesn't support \s
:
help::[\r\n\t\f ]*(.*?)[\r\n\t\f ]*?(?:\*\/|-->)
You can also use Which prevents any un-necassary selection making this easier to use also:
help::[\r\n\t\f ]*(.*?)(?=[\r\n\t\f ]*?\*\/|[\r\n\t\f ]*?-->)
You could use this as a funky .replace
but it might result in quirky behavior:
/\/\*[\r\n\t\f ]*help::|<!--[\r\n\t\f ]*help::|[\r\n\t\f ]\*\/|[\r\n\t\f ]*-->/g
help:: Matches the text "help::"
[\r\n\t\f ]* Matches any whitespace character 0-unlimited times
(.*?) Captures the text
[\r\n\t\f ]*? Matches all whitespace
(?: Start of non-capture group
\*\/ Matches "*/"
| OR
--> Matches "-->"
) End non capture group
[\r\n\t\f ]
\r Carriage return
\n Newline
\t Tab
\f Formfeed
Space
help:: Matches "help::"
[\r\n\t\f ]* Matches all whitespace 0-unlimited
(.*?) Captures all text until...
(?= Start positive lookahead
[\r\n\t\f ]*? Match whitespace 0-unlimited
\*\/ Matches "*/"
| OR
[\r\n\t\f ]*? Match whitespace 0-unlimited
--> Matches "-->"
)
Upvotes: 8
Reputation: 4466
var regExArray = [['\\/\\* help::','*/'],['<!-- help::','-->']]
var regexMatchers = regExArray.map(function(item){
return new RegExp('^'+item[0]+'(.*)'+item[1]+'$')})
function RemoveEndingTagsNew(comment){
var newComment;
regexMatchers.forEach(function(regEx,index){
if(regEx.test(comment)){
newComment=comment.replace(/.* help::/,"").replace(regExArray[index][1],"")
}
});
return newComment || comment;
}
Its longer version, but doesnt remove comments if starting and ending comment tags doesnt match.
Demo: https://jsfiddle.net/6bbxzyjg/2/
Upvotes: 2
Reputation: 1013
var str = '<!-- A comment -->';
var newstr = str.replace(/<\!--(.*?)-->/, '$1');
console.log(newstr); // A comment
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace
Upvotes: 2
Reputation: 1774
You can add more languages as needed:
help::.*?\s(.*)(?:.*?\s\*\/|.*?\s\-->)
Example: https://regex101.com/r/rK2kU0/1
Upvotes: 3