Home > Enterprise >  javascript using regex to get multiple separates including text string separator
javascript using regex to get multiple separates including text string separator

Time:09-30

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.

CodePudding user response:

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.

CodePudding user response:

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.

  • Related