How can I find everything between the hyphens with regex? Array answer for below should be ["aaa","bbb","ccc","ddd"]
<script>
myRe= new RegExp ("xxxxxx");
myArray = myRe.exec("-aaa-bbb-ccc-ddd-");
</script>
Also... what happens if there are comma's in the string and they need to be included in the array?
Is this below alright...?
["a,a,a","bbb","ccc","ddd"]
One quick and easy solution is to look for word characters in the string:
"-aaa-bbb-ccc-ddd-".match(/[\w]+/g)
This will return ["aaa", "bbb", "ccc", "ddd"]
If you needed to match strings with commas in them as well then you could add a comma to the capture group:
// added ',' to [\w,]
"-a,a,a-bbb-ccc-ddd-".match(/[\w,]+/g)
This will return ["a,a,a", "bbb", "ccc", "ddd"]
This solution won't scale well if you're looking for anything to be matched between some '-'s, but if you have a simple use case then I'd say use a simple match like the ones demonstrated above.
Update
Since your comment said you need to match anything between '-'s, you can use the following regex:
/[^\-]+/g
This will match anything that is not a '-' in groups, so:
"-a,@$#$a,a-bbb-ccc-ddd-".match(/[^\-]+/g)
will return ["a,@$#$a,a", "bbb", "ccc", "ddd"]
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.