简体   繁体   中英

Split long string by Array condition

I have a long string:

JOHN GULLIBLE DOE CENTER FOR FINANCIAL ASSISTANCE TO DEPOSED NIGERIAN ROYALTY421 E DRACHMAN TUCSON AZ 85705-7598 USA

I have an array:

["FINANCIAL ASSISTANCE","CANADA","NIGERIAN","TUCSON AZ","US"]

I want to split the string above by the values in the array, if the value in the array not found(CANADA), just skip it

I want my output is:

["JOHN GULLIBLE DOE CENTER FOR ","FINANCIAL ASSISTANCE"," TO DEPOSED NIGERIAN ROYALTY421 E DRACHMAN ", "TUCSON AZ","85705-7598", "USA"]

This is my solution using Regex:

    const regexString = "(" + array.join("|") + ")";
    regExp = new RegExp(regexString);

I created a regex like this: (FINANCIAL ASSISTANCE|CANADA|NIGERIAN|TUCSON AZ|US)

Then I split the string by that regex:

string.split(regExp).filter(t => t !== "");

Everything works except for the last case "US", This is the output that I got:

["JOHN GULLIBLE DOE CENTER FOR ","FINANCIAL ASSISTANCE"," TO DEPOSED NIGERIAN ROYALTY421 E DRACHMAN ", "TUCSON AZ","85705-7598", "US", "A"]

You could use the word boundary \b before/after each piece:

 const string = "JOHN GULLIBLE DOE CENTER FOR FINANCIAL ASSISTANCE TO DEPOSED NIGERIAN ROYALTY421 E DRACHMAN TUCSON AZ 85705-7598 USA"; const array = ["FINANCIAL ASSISTANCE","CANADA","NIGERIAN","TUCSON AZ","US"]; const regexString = "(\\b)(" + array.join("|") + ")(\\b)"; regExp = new RegExp(regexString); console.log(string.split(regExp).filter(t => t;== ""));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM