Javascript: split function

 let str = 'My-name-is-Lord-Voldemort';
let arr = str.split('-');

Here i’ll get the array

arr[0] = 'My' ; arr[1] = 'name'

What should i do to get this

arr[0] = 'My'; arr[1] = '-';
arr[2] = 'name; arr[3] = '-';

Are you familiar with RegEx? The only way I can think of doing this without using loops and such would be to split it with a Regular Expression. One you use RegEx, this can be done easily. Look into RegEx anchor metacharacters and see if you can find the one that will give you the result you need.

1 Like

My question is do you really need to capture the “-” in the array? Depending on how the array be used later, it may not be necessary to capture the “-”. If you can provide some context on how you plan to use, maybe we can offer a different approach.

I want this result:

let res = '3 * 3' ;
// res is now equal to 9

I know about eval function which will do the job. But i want to do it using a custom function.

I see, so you want to split the string you have built with a user’s calculator input and be able to capture the +, -, *, /, etc… to do further processing?

If that is the case, I definitely recommend using a regular expression with the match method to generate such an array. It could also be doing with a for loop using some type of object lookup for the various operators. If you go the regular expression route, then practice writing how you would split the string on a single operator and then multiple operators. If you get stuck, show us your code and we will try to assist you.

How do i convert'*'into * operator

You can’t convert a string to a math operator, but you can convert a string to a function that multiplies numbers…

ps. are you sure you want to do this? When the code starts getting weird, it is best to step back and ask if there is a better way forward.

This is the project i’m working on: