最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Split string by whitespace and dashes - Stack Overflow

programmeradmin3浏览0评论

What is the best way to split a string up into an array of 'words'. Splitting by whitespace but also by dashes, where a dash bees part of the previous 'word'.

Example:

"This is an example-string to

demo what I mean"

[ "This", "is" , "an" , "example-" , "string" , "to" , "demo" , "what" , "I" , "mean" ]

Edit: I'm an idiot - It is this:

someString.replace(/-/g, "- ").split(/[\s]/); // retain dashes

What is the best way to split a string up into an array of 'words'. Splitting by whitespace but also by dashes, where a dash bees part of the previous 'word'.

Example:

"This is an example-string to

demo what I mean"

[ "This", "is" , "an" , "example-" , "string" , "to" , "demo" , "what" , "I" , "mean" ]

Edit: I'm an idiot - It is this:

someString.replace(/-/g, "- ").split(/[\s]/); // retain dashes
Share edited Mar 2, 2012 at 14:57 Adamarla asked Mar 2, 2012 at 14:48 AdamarlaAdamarla 81210 silver badges22 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 7

Splitting won't work if the delimiter should stay in the result, because the delimiter is always consumed.

Use .match instead:

"This is an example-string to demo what I mean".match(/[^\s-]+-?/g);
// ["This", "is", "an", "example-", "string", "to", "demo", "what", "I", "mean"]

This regexp matches one or more characters that are not spaces/dashes, and an optional dash following it. With the g flag, all matches are returned.

发布评论

评论列表(0)

  1. 暂无评论