1

I have a Javascript string.

var str = "an eye";

I want to split the string to get all the alphabets in an array using split() and regex. Meaning I want,

['a','n','e','y','e']

I used the following regex in match() to get the array:

var reg = /[a-z]/gi;

But, when I use the same regex in split(), it gives me an array of spaces.

["", "", " ", "", "", ""]

Please help me understand what i am missing here. I am new to both javascript and regex. TIA.

2
  • 1
    The implicit meaning of split is "split at". Commented Mar 9, 2018 at 19:15
  • 2
    @Imad062 split uses the match as a delimiter and returns the substrings from between the matches along with any captured groups from the regex matches. Both the answers posted using split will also return a space with the n ("n " instead of "n"). You should use match instead, and you can still call reverse on the array and anything else you want to do, such as str.match(/[a-z]/gi).reverse().join('');. Commented Mar 9, 2018 at 19:33

2 Answers 2

3

You've got spaces because when you split by char the split() function consumes that char. Use positive lookahead (?=) instead. See regex demo.

var text = 'an eye'
console.log(text.split(/(?=[a-z])/i))

Sign up to request clarification or add additional context in comments.

Comments

2

You're pretty close! split will remove the items it matches and return the strings in-between each removed item as an array.

You want match instead, which returns an array of the items it matches:

str.match(/[a-z]/gi);

To get a better understanding of these methods, check out the split and match documentation.

4 Comments

I want to use split() so that I can use reverse() and join() to reverse the string. I can get the results using match() but I can't get an understading of how split() works.
@Imad062 reverse and join are functions on Array.prototype. You can use them on any array whether it comes from split, match or anything else, like [1,2,3].reverse().join(',') === '3,2,1'.
Thanks For clarifying. I see that using match in these cases is more useful.
@Imad062 It's not only "more useful", it's a more appropriate function considering your goal.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.