Extract words with RegEx

前端 未结 3 421
情深已故
情深已故 2020-12-12 06:33

I am new with RegEx, but it would be very useful to use it for my project. What I want to do in Javascript is this :

I have this kind of string \"/this/is/an/example

相关标签:
3条回答
  • 2020-12-12 06:55

    Use split()

    The split() method splits a String object into an array of strings by separating the string into substrings, using a specified separator string to determine where to make each split.

    var str = "/this/is/a/test"; 
    var array = str.split('/');
    console.log(array);

    In case you want to do with regex.

    var str = "/this/is/a/test"; 
    var patt1 = /(\w+)/g;
    var result = str.match(patt1)
    console.log(result);

    0 讨论(0)
  • 2020-12-12 07:07

    Well I guess it depends on your definition of 'word', there is a 'word character' match which might be what you want:

    var patt1 = /(\w+)/g;
    

    Here is a working example of the regex

    Full JS example:

    var str = "/this/is/a/test"; 
    var patt1 = /(\w+)/g;
    var match = str.match(patt1);
    
    var output = match.join(", ");
    console.log(output);

    0 讨论(0)
  • 2020-12-12 07:09

    You can use this regex: /\b[^\d\W]+\b/g, to have a specific word just access the index in the array. e.g result[0] == this

    var str = "/this/is/a/test";
    var patt1 = /\b[^\d\W]+\b/g;
    var result = str.match(patt1);
    document.getElementById("demo").innerHTML = result;
    <span id="demo"></span>

    0 讨论(0)
提交回复
热议问题