0

I have a problem I am quite stuck with. I have a snippet of code that I am reading in as a string, but I would like to remove a specific portion of it.

/**
 * This file is autoupdated by build.xml in order to set revision id.
 *
 * @author Damian Minkov
 */
public class RevisionID
{
    /**
     * The revision ID.
     */
    public static final String REVISION_ID="0";
}

For example, the above snippet of code. I would like to replace all the comments (everything between /** and */).

How would I go about doing this?

Right now, this is the attempt I am working with;

    var sposC = temp.indexOf('/*');
    console.log(sposC);
    var eposC = temp.indexOf('*/');
    console.log(eposC);
    var temp1 = temp.replace(eposC + sposC, '1');

It is not working though, so may someone please help me.

Brian Lui
  • 27
  • 2
  • 8
  • use a regular expression to remove the comments. See here: http://stackoverflow.com/questions/5989315/regex-for-match-replacing-javascript-comments-both-multiline-and-inline – sjkm Nov 23 '13 at 00:27

2 Answers2

0

The replace function searches for a string and replaces it (e.g. replace "find" with "fin"). It does not replace a specific section of a string. Try something like this instead:

function replaceBetween(originalString, start, end, replacement)
{
    return originalString.substr(0,start)+replacement+originalString.substr(end);
}

var sposC = temp.indexOf('/*');
var eposC = temp.indexOf('*/')+2;
var temp1 = replaceBetween(temp, sposC, eposC, 'Whatever you want to replace it with');
Flight Odyssey
  • 2,267
  • 18
  • 25
0

You can replace all of your temp.indexOf and temp.replace with a regular expression replacement. Incidentally, both sposC and eposC are going to be numbers, and replace wants a string or regex, so if you insist on keeping the indexOf calls, you can't use them as parameters to replace anyway.

var newString = temp.replace(/\/\*(?:[^\*]|\*[^\/])*\*\//, '1');

That's what it should look like. If you don't really want the comment to be replaced with 1 all the time and need the actual contents of the comment for whatever reason, get rid of the ?: to capture the contents and refer to it in the replacement as $1.

If, at some point, you need to be able to read or modify the regex, you should use neither of these approaches. No one can read regex. Use a parser generator like peg.js instead.

sqykly
  • 1,586
  • 10
  • 16