1

I have a string that I wish to split using multiple separators (including a string separator which I can't find much information on)

I wish to split the string on occurrences of / and the string AGL but that the moment when I print out the array array[0] I just get L. Quotes around the string AGL don't seem to make a difference.

str = "LLF ABC TEMP / HERE / RET / UP TP 12F AGL PLACENAME VALUES / AVM / ABC / PPP / END"
var array = [];
array = str.split(/(AGL|\/|)/g);  

So at the end my array should have 9 items.

LLF ABC TEMP

HERE

RET

UP TP 12F

PLACENAME VALUES

AVM

ABC

PPP

END

Thank you.

1

2 Answers 2

2

You can use

str = "LLF ABC TEMP / HERE / RET / UP TP 12F AGL PLACENAME VALUES / AVM / ABC / PPP / END"
var array = str.split(/\s*(?:AGL|\/)\s*/);
console.log(array);

Note you do not need /g flag with .split, it is the default behavior.

The \s*(?:AGL|\/)\s* regex matches

  • \s* - zero or more whitespaces
  • (?:AGL|\/) - a non-capturing group (so that its value could not land in the resulting array) matching either AGL or /
  • \s* - zero or more whitespaces.
Sign up to request clarification or add additional context in comments.

Comments

0

I think this is what you were trying to do, was a little tricky, since you need to use the lookbehind group:

str = "LLF ABC TEMP / HERE / RET / UP TP 12F AGL PLACENAME VALUES / AVM / ABC / PPP / END"
var array = [];
array = str.match(/(\b(AGL)|(\w+([^\/])(?!(AGL)))+\b)/g); 
console.log(array)
This is the regex (/(\b(AGL)|(\w+([^/])(?!(AGL)))+\b)/g). I also used match instead of split, so you don't get Undefined, empty string values and '/' values in your array.

If this isn't exactly what you were looking for, see: regexr.com/66jhd It's a great little web tool for testing regex.

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.