【发布时间】:2017-04-03 07:20:32
【问题描述】:
我曾在 PHP 中使用 preg_replace,但我不得不将其移至 JavaScript 代码,但它在那里不起作用。我在这里搜索了主题,但没有找到适合我的解决方案...... 我的 PHP 看起来像:
preg_replace('/^\d+_/', '', $docTypes);
现在,我的 JS 看起来很重要,var documentTypes 是 object:
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