-1

I wanted to split a string using regex expression.

The string is:

var str = 'i want @masala tea@'

I want this string to be splitted into the array ['i want','masala tea']

What I have tried so far was:

var arr = str.split(/^@.*@$/);

but this did not work.

1

3 Answers 3

1

Don't use spilt function for this case. use replace funtion like this:

var str='i want @masala tea@';
console.log(str.replace(/@/gi, "")); //i want masala tea.

Thanks.

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

1 Comment

I believe OP asked for an array using, not a resulting string
1

You can split your message on each '@' and then filter empty items. If you need to remove whitespace characters from each string use .map(...) function.

'i want @masala tea@'.split('@').filter(e => e != ""); 
//["i want ", "masala tea"]
'i want @masala tea@'.split('@').map(e => e.trim()).filter(e => e != ""); 
//["i want", "masala tea"]

Comments

0

Yes, you can split string using regex expression. Try this. i thing it will solve your problem.

let yourString = 'i want @masala tea@'; // your string 

// function that return exactly what you want
let outputArr = (string) => {
    return string.trim().match(/[^@]+/g).map(item => item.trim());
}

console.log(outputArr(yourString)); 
//(2) ["i want", "masala tea"]

Comments

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.