开发者

Javascript regex match only characters

From a string I need to pull out any word beginning with dog. Eg. "dog", "doggy", "doggystyle"开发者_开发知识库.

Howto?


Use /(\bdog\w*)/g, e.g.

"dog dogman doggy notdoggy doggyagain".match(/(\bdog\w*)/g)
// => ["dog", "dogman", "doggy", "doggyagain"]

The /g flag is important. It makes the regex match all occurences, not only the first.


\bdog\w*

\b is a word boundary

\w is a word character

* means 0 or more


Trivally, you could use the split() function combined with the substr() function to do this as well. e.g.

var str = "dog doggy other doggystyle";

// Split string by spaces.
var result = str.split(" ");  // Split on the space character.

// Iterate through array, split on space.
for(i = 0; i < result.length; i++){

   // Identify words that start with "dog"
   if(result[i].substr(0, 3) == "dog")
   {
      // Word starts with dog.  Do something with it here.
   }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜