【问题标题】:PHP preg_replace in javascriptjavascript中的PHP preg_replace
【发布时间】:2017-04-03 07:20:32
【问题描述】:

我曾在 PHP 中使用 preg_replace,但我不得不将其移至 JavaScript 代码,但它在那里不起作用。我在这里搜索了主题,但没有找到适合我的解决方案...... 我的 PHP 看起来像:

preg_replace('/^\d+_/', '', $docTypes);

现在,我的 JS 看起来很重要,var documentTypesobject

   var documentTypesObj = {};
   var counter = 0;
   {foreach $documentTypes as $key =>$value}
   documentTypesObj[counter + '_' + {$key}] = {$value};
   counter++;
   {/foreach}

    var documentTypes = documentTypesObj;

    documentTypes = documentTypes.map(d => { return d.replace(/^\d+_/g, "")});

    console.log(documentTypes);

var documentTypes 内部是带前缀的值,我必须将其删除。值例如:

0_xxxx
1_xxxx
2_xxxx

感谢您的建议!

【问题讨论】:

  • 你在结尾加了一个/,一定是/^\d+_/g
  • ^^^ 和 documentTypes = documentTypes.replace(/^\d+_/, ''); 您必须将其分配回变量以更新其值,并且不需要 g 标志。
  • @Tushar 代码已编辑

标签: javascript php preg-replace


【解决方案1】:

如果是数组:

var docs = ["0_xxx", "1_yyy", "2_zzzz"];
docs = docs.map(d => { return d.replace(/^\d+_/g, "")});

【讨论】:

  • 实际上它是对象,当我使用您的解决方案时,console.log 说 docs.map 不是一个函数..:( 但它也告诉我,当我尝试使用 forEach() 和其他功能...
【解决方案2】:
<script type="text/javascript">
    documentTypes = '0_xxxx';
    documentTypes = documentTypes.replace(/^\d+_/, '');
    document.write(documentTypes);
</script>    

【讨论】:

  • 没有解释?仅代码答案对未来的读者没有帮助。请edit回答并添加说明。
【解决方案3】:

不确定您的输入字符串,问题可能是因为您在字符串中有换行符或回车。如果是这样,您正在寻找的解决方案可能是这样的:

var documentTypes = '0_xxxx\n\
1_xxxx\n\
2_xxxx';

documentTypes = documentTypes.replace(/(^\d+_|[\r\n]+\d+_)/gm,'');

【讨论】:

    猜你喜欢
    • 2010-09-29
    • 2011-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-14
    • 2013-08-03
    相关资源
    最近更新 更多