【问题标题】:Javascript - cutting out specific range of substrings from a stringJavascript - 从字符串中删除特定范围的子字符串
【发布时间】:2013-11-23 00:24:10
【问题描述】:

我遇到了一个问题,我很纠结。我有一段代码作为字符串读取,但我想删除它的特定部分。

/**
 * 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";
}

比如上面sn-p的代码。我想替换所有 cmets(/** 和 */ 之间的所有内容)。

我该怎么做呢?

现在,这是我正在尝试的;

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

它不起作用,所以请有人帮助我。

【问题讨论】:

标签: javascript string replace substring


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    您可以用正则表达式替换所有temp.indexOftemp.replace。顺便说一句,sposCeposC 都将是数字,replace 需要字符串或正则表达式,因此如果您坚持保留 indexOf 调用,则不能将它们用作 replace 的参数无论如何。

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

    这就是它应该的样子。如果您真的不想一直将评论替换为 1 并且出于任何原因需要评论的实际内容,请去掉 ?: 以捕获内容并在替换中将其引用为$1.

    如果在某些时候,您需要能够读取或修改正则表达式,则不应使用这两种方法。没有人可以阅读正则表达式。请改用 peg.js 之类的解析器生成器。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-14
      • 2015-10-02
      • 2021-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多