我有一个问题我很困惑。我有一段代码,我正在读作一个字符串,但我想删除它的一个特定部分。
/**
* 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";
}
例如,上面的代码片段。我想替换所有注释(/ **和* /之间的所有内容。)
我将如何做到这一点?
现在,这是我正在尝试的尝试;
var sposC = temp.indexOf('/*');
console.log(sposC);
var eposC = temp.indexOf('*/');
console.log(eposC);
var temp1 = temp.replace(eposC + sposC, '1');
虽然不行,所以有人可以帮助我。
答案 0 :(得分:0)
replace
函数搜索字符串并替换它(例如将“find”替换为“fin”)。它不会替换字符串的特定部分。尝试这样的事情:
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');
答案 1 :(得分:0)
您可以使用正则表达式替换替换所有temp.indexOf
和temp.replace
。顺便提一下,sposC
和eposC
都是数字,而replace
想要一个字符串或正则表达式,所以如果你坚持要保留indexOf
个电话,你就不能无论如何,将它们用作replace
的参数。
var newString = temp.replace(/\/\*(?:[^\*]|\*[^\/])*\*\//, '1');
这应该是什么样子。如果您不希望评论一直被1
替换,并且出于任何原因需要评论的实际内容,请删除?:
以捕获内容并引用它在替换为$1
。
如果在某些时候,您需要能够阅读或修改正则表达式,则不应使用这些方法。没有人可以阅读正则表达式。使用像peg.js这样的解析器生成器。