简体   繁体   中英

Extract words with RegEx

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" and I would like to extract each word of that string, that is to say :

"/this/is/an/example" -> this, is, an, example. And then use each word.

Up to now, I did :

var str = "/this/is/a/test"; 
var patt1 = /\/*/g;
var result = str.match(patt1);
document.getElementById("demo").innerHTML = result;

and it returns me : /,,,,,/,,,/,,/,,,,,

I know that I will have to use .slice function next if I can identify the position of each "/" by using search for instance but using search it only returns me the index of the first "/" that is to say in this case 0.

I cannot find out.

Any Idea ?

Thanks in advance !

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);

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);

You can use this regex: /\\b[^\\d\\W]+\\b/g , to have a specific word just access the index in the array. eg 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM