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:
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:
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:
This will match anything that is not a ‘-‘ in groups, so:
will return
["a,@$#$a,a", "bbb", "ccc", "ddd"]