如何使用 JavaScript(不是 jQuery)从字符串中过滤前缀和 trim 词

How to filter prefix and trim words from a string with JavaScript (not jQuery)

我从来都不擅长字符串操作,现在我被困住了。所以长字符串有以下内容:

[desktop-detected display-settings  main-boxed  pace-done header-function-fixed nav-function-fixed nav-function-hidden nav-function-minify mod-sound mod-font]

我想过滤并保留带有 nav-、header- 和 mod-* 前缀的字符串,因此清理后的字符串应该如下所示:

[header-function-fixed nav-function-fixed nav-function-hidden nav-function-minify mod-sound mod-font]

完全没有头绪,一头雾水...

拆分、过滤和合并

var result = '[' + string.split(/[^\w-]+/).filter(function(item) {
    return /^(nav|header|mod)-/i.test(item);
}).join(' ') + ']';

JSFiddle 演示:https://jsfiddle.net/c3nff3p6/2/

/[^\w-]+/ 正在通过不匹配单词或破折号作为分隔符将短语拆分为数组。

/^(nav|header|mod)-/i 如果项目以这些值中的任何一个开头,后跟破折号,不区分大小写,则匹配。

其他解决方案,谢谢

'[' + string.slice(1, -1).split(/\s+/).filter(str => /^(nav|header|mod)-/.test(str)).join(' ') + ']'

使用匹配

'[' + string.slice(1, -1).match(/\b(nav|header|mod)-\S*/g).join(' ') + ']'