2013-11-23 147 views
0

我有一個問題,我很困擾。我有一段代碼作爲字符串閱讀,但我想刪除它的特定部分。Javascript - 從字符串中刪除特定範圍的子串

/** 
* 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

使用正則表達式刪除註釋。 請參閱這裏:http://stackoverflow.com/questions/5989315/regex-for-match-replacing-javascript-comments-both-multiline-and-inline – sjkm

回答

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'); 
0

您可以用正則表達式替換替換所有temp.indexOftemp.replace的。順便提一下,sposCeposC都是數字,而replace需要一個字符串或正則表達式,因此如果您堅持保留indexOf調用,則無論如何都不能將它們用作replace的參數。

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

這就是它應該的樣子。如果您不希望評論始終以1取代,並且無論出於何種原因都需要評論的實際內容,請刪除?:以獲取內容並將其替換爲$1

如果在某些時候需要能夠讀取或修改正則表達式,則應該既不使用這些方法。沒有人可以閱讀正則表達式。改用peg.js之類的解析器生成器。

相關問題