PHP 函数到 Javascript : scan string and add words in array

标签 php javascript regex preg-match-all

我正在尝试将此 php 函数转换为 javascript:

function sanitize_words($string,$limit=false) {
    preg_match_all("/\p{L}[\p{L}\p{Mn}\p{Pd}'\x{2019}]{1,}/u",$string,$matches,PREG_PATTERN_ORDER);
    return $matches[0];
}

基本上,它需要这个字符串:

$string = "Why hello, how are you?"
$array = sanitize_words($string);

并将其转换为数组:

$array[0] = 'Why';
$array[1] = 'hello';
$array[2] = 'how';
$array[3] = 'are';
$array[4] = 'you';

它在 php 上运行得很好,但我不知道如何在 javascript 上实现它,因为 phpjs.org 中没有 preg_match_all 。有任何想法吗?谢谢。

最佳答案

使用String.match方法,并在正则表达式上设置了 g (全局)标志。 \w 相当于[a-zA-Z0-9_]。如果您确实想要模仿当前模式,请使用 this page作为转换 JavaScript 模式中字符属性的引用。

function sanitize_words($string) {
    return $string.match(/\w+/g);
}

关于PHP 函数到 Javascript : scan string and add words in array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8404557/

相关文章:

php - 正则表达式查找html div类内容和数据属性? (preg_match_all)

javascript - 带连字符的 YouTube 网址测试器

php - Mysql LIKE 通配符有时存在值

javascript - 嵌套/共享 Angular 应用程序

php - 如何阻止 MySQL 十进制字段被四舍五入?

javascript - 将动态形式序列化为对象数组

javascript - 在 JavaScript 测试中模拟 setInterval 返回的 ID

javascript - AB1234567 的正则表达式

php - 使用 PHP/MySQL 连接 2 个具有多列的表

php - Rest API(高级或专业帐户)