Javascript-从字符串中删除特定范围的子字符串
我有一个问题,我一直很困扰。我有一段作为字符串读取的代码,但我想删除其中的特定部分Javascript-从字符串中删除特定范围的子字符串,javascript,string,replace,substring,Javascript,String,Replace,Substring,我有一个问题,我一直很困扰。我有一段作为字符串读取的代码,但我想删除其中的特定部分 /** * 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 REVIS
/**
* 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');
但是它不起作用,所以请有人帮助我。函数搜索字符串并将其替换(例如,将“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');
您可以用正则表达式替换所有的
temp.indexOf
和temp.replace
。顺便说一句,sposC
和eposC
都将是数字,replace
需要字符串或正则表达式,因此如果您坚持保留indexOf
调用,您无论如何都不能将它们用作replace
的参数
var newString = temp.replace(/\/\*(?:[^\*]|\*[^\/])*\*\//, '1');
应该是这样的。如果您真的不希望注释始终被替换为1
,并且出于任何原因需要注释的实际内容,请删除?:
以捕获内容,并在替换中将其称为$1
如果在某个时候,您需要能够读取或修改正则表达式,那么您不应该使用这两种方法。没有人能读正则表达式。改用peg.js之类的解析器生成器。使用正则表达式删除注释。请看这里: