2017-04-03 44 views
-1

我曾在PHP工作preg_replace,但我不得不将它移动到JavaScript代码,它不起作用。我已经在这里搜查的话题,但还没有找到工作的解决方案,我......我 PHP看起来像:PHP preg_replace in javascript

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

Inside var documentTypes是带有前缀的值,我必须删除它。数值例如:

0_xxxx 
1_xxxx 
2_xxxx 

谢谢您的建议!

+0

你在最后加了一个'/',它必须是'/^\ d + _/g'。 –

+2

^^^和'documentTypes = documentTypes.replace(/^\ d + _ /,'');'你必须把它赋值给变量来更新它的值并且不需要'g'标志。 – Tushar

+0

@Tushar代码编辑 – hstur

回答

1

如果它是一个数组:

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

实际上它是对象,当我使用你的解决方案时,console.log说,docs.map不是一个函数.. :(但它告诉我,当我尝试使用'forEach()'和其他函数... – hstur

2
<script type="text/javascript"> 
    documentTypes = '0_xxxx'; 
    documentTypes = documentTypes.replace(/^\d+_/, ''); 
    document.write(documentTypes); 
</script>  
+2

没有解释?只有代码答案对未来的读者没有帮助。请[编辑]答案并添加解释。 – Tushar

+0

好的........... –

0

不知道在你输入的字符串,问题可能是becouse你有换行或携带的字符串返回。如果是这样,你正在寻找的解决方案可能是这样的:

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

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