Search code examples
javascriptstringfiltersplitprefix

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


I have never been good with string manipulation and I am now stuck. So the long string has the following:

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

I want to filter and keep the string with the nav-, header-, and mod-* prefixes, so the cleaned up string should look like:

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

I have no idea how to start, completely clueless...


Solution

  • split, filter, and join

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

    JSFiddle Demo: https://jsfiddle.net/c3nff3p6/2/

    /[^\w-]+/ is splitting the phrase into an array by not matching words or dashes as the separator.

    /^(nav|header|mod)-/i matches if the item starts with either of those values followed by dash, case insensitive.

    Other solutions, thanks @Tushar.

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

    using match

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