将PHP preg_replace转换为Javascript替换

时间:2022-10-11 22:26:05

Please could someone help me convert the PHP preg_replace to Javascript replace.

请有人帮我转换PHP preg_replace到Javascript替换。

PHP

PHP

<?php
$str = 'Test * Testing';
preg_replace('/[^A-Za-z 0-9\~\%\.\:\_\\-\&]/', '', $str));
?>

Javascript

使用Javascript

<script>
var str = 'Test * Testing';
str.replace(/[^A-Za-z 0-9\~\%\.\:\_\\-\&]/gi, '');
<script>

EDIT: The solution suggested is more elegent (\w) and I'll be using that in future.

编辑:建议的解决方案更加优雅(\ w),我将来会使用它。

Thanks

谢谢

1 个解决方案

#1


2  

Why did you removed the character class, just keep it:

为什么删除了字符类,只需保留它:

str.replace(/[^A-Za-z 0-9~%.:_\\&-]/gi, '');

Also [a-zA-Z0-9_] can be shortened to \w:

[a-zA-Z0-9_]也可以缩短为\ w:

str.replace(/[^\w ~%.:\\&-]/gi, '');

#1


2  

Why did you removed the character class, just keep it:

为什么删除了字符类,只需保留它:

str.replace(/[^A-Za-z 0-9~%.:_\\&-]/gi, '');

Also [a-zA-Z0-9_] can be shortened to \w:

[a-zA-Z0-9_]也可以缩短为\ w:

str.replace(/[^\w ~%.:\\&-]/gi, '');