如何在javascript中的行空格/分隔符上拆分字符串

时间:2016-02-07 13:28:48

标签: javascript regex

我有以下来自cnn.com的标题/短语/句子数组:

0: "WorldPoliticsMoneyOpinionHealthEntertainmentStyleTravelSportsVideoLive TV Search »↵U.S."
1: "Edition+↵↵↵GOP debate: What we learned↵↵Governors get their revenge, and Rubio gets knocked around↵Cruz lies about CNN reportPoll: Trump's N.H. lead grows, not Sanders'"
2: "Reality CheckCandidate grades↵Top stories↵↵N."
3: "Korea: Launch a success↵CNN to host Dem debate in Flint↵'State of the Union' to feature Trump, Clinton, Sanders↵Sanders, Larry David NOT same person↵Video shows airport workers with laptop used in Somalia in-flight jet blast↵Swaziland sends elephants to U.S."
4: "News and buzz↵Iran: Saudis don't stand a chance↵40 m↵Rescuers scour quake rubble↵Reporter groped live on air↵'Bonnie and Clyde' phoned farewells↵Woman dies in bakery mixer ↵Pluto has 'floating hills'↵U.S."
5: "High schooler weighs NBA draft↵Samsung to reveal new smartphones↵Super Bowl 50↵↵Who'll play Super Bowl halftime show?"
6: "What time does Super Bowl start?"
7: "Manning vs Newton: Who'll win?"
8: "Recommended↵You have to see this↵↵Twitter bares cleavage for Susan Sarandon↵↵Actress makes fashion statement on red carpet↵↵Bernie Sanders makes a cameo on 'SNL'↵↵The real reason Mary Ingalls went blind↵CNNMoney↵↵One of the coolest ways to commute↵Here's another use for drones↵How to get your weirdest ideas made in U.S."
9: "Politics↵↵The GOP establishment's bloodbath in New Hampshire↵Fact checking the GOP debate↵Ted Cruz is wrong about CNN's reporting↵Rubio in firing line at GOP debate↵Steinem: Young women back Sanders to meet boys↵Opinions↵↵Debate Coach: Only one candidate got an A↵Christie's scorched earth attack plan↵What happened to Boy Wonder?"
10: "The legal profession's drinking problem↵Is future bleak for Super Bowl?"
11: "From our partners↵8 out-of-the-box workouts every daredevil needs to try People↵This camera drone shoots the best selfies Wallpaper↵A brilliant strategy to pay off your credit card NextAdvisor↵Tech↵Entertainment↵↵Earth, Wind & Fire founder dies at 74↵30 years later, Janet Jackson is still in 'Control'↵Bob Elliott, half of duo Bob and Ray, dies at 92↵What's streaming in February↵Sports↵Cam Newton named NFL MVP↵Favre headlines 2016 HOF class↵Ex-WWE star lands first UFC opponent↵NFLer wins award after bout with cancer↵The Super Bowl plays that changed lives↵Health↵↵New Hampshire town's surprising warrior against heroin↵Why can't we just kill all mosquitoes?"
12: "Actress fights bipolar disorder stigma↵Eating fish could stave off Alzheimer's, study says↵Travel↵↵National parks: The roots of 'America's best idea'↵Incredible scenes from the High Arctic↵World's 25 top tourism destinations↵The newest airport amenity?"
13: "Movie theaters↵Living↵↵Long road to becoming a Budweiser Clydesdale↵Twitter bares cleavage for Susan Sarandon↵Young reader's list of #1000BlackGirlBooks↵All the festive facts about Mardi Gras↵Video ↵Videos you should see↵↵Can YOU tell which one is the mom?"
14: "Be careful this doesn't happen to your dog↵↵Interrogation video released of ex-cop convicted of rape↵↵Woman dies in bakery mixer at grocery store↵↵Wild sea lion pup wanders into restaurant↵↵Kindergartner dies playing on school monkey bars↵↵Uber driver picks up rap group and then ..."
15: "Actor declared dead after botched hanging scene↵↵Ghostly figures appear from depths of the ocean↵Just for fun↵↵'Trumpertantrum' goes viral↵↵Adorable polar bear cub gets a name↵↵Lawmaker gets hit in the face with ..."
16: "Rob 'Gronk' Gronkowski's secret stripper past↵↵Rare wild jaguar spotted living in U.S."
17: "More from CNN ↵Beyond the Call of Duty↵↵Officers break rules, save baby↵↵Police catch girl who jumped from burning building↵↵Remembering the officer known as 'Superman'↵Upstarts↵↵Can daily text message help you?"
18: "This plastic toilet could save lives↵↵Startup founder: The U.S."
19: "Great Big Story ↵↵World's best female rock climber is 14↵↵Why you were forced to square dance↵↵Beware of the Bobbit worm↵Photos ↵↵The week in politics↵↵The week in 33 photos↵↵Bingo halls and rock-star dreams↵↵First 'Super Bowl' wasn't exactly super↵From our partners ↵Healthgrades↵The best diet for psoriasis↵10 stretching do's and don'ts↵Drugs that raise your blood sugar↵6 reasons to see a gastroenterologist↵Charities that support MS research↵Food & Wine↵50 Super Bowl Recipes for Super Bowl 50↵Best chocolate in the US↵Romantic dishes↵All-American appetizers↵Best crock pot and slow cooker recipes↵NextAdvisor↵The best credit cards for 2016↵2 credit cards are offering 0% interest until November 2017↵The unbelievable 6% cash back card↵A major credit card issuer just extended their best 0% APR credit card offer↵10 best balance transfer credit cards for 2016↵LendingTree↵Rates hit 3.02% APR (15 yr). See if you'"
20: "A loan that boosts your credit score?"
21: "These 4 balance transfer cards could help you save big↵Fastest way to pay off $10,000 in credit card debt↵4 cards with jaw-droppingly long 0% intro APR↵Time Lifestyle↵Dubai reinvents itself as a global design capital↵20 under 40: The design stars of tomorrow↵This stadium is made entirely of bamboo↵One button replaces all of your wireless remotes↵Dine like a mermaid in Hong Kong↵Motley Fool↵Shark Tank just revealed a trillion-dollar idea↵Forget Apple! Here'"
22: "How 1 man turned $10,600 into $8,016,867↵5 rock-solid dividend secrets any retiree can use↵Trulia Home Search↵Houston real estate↵Time to sell? What's your home worth?"
23: "Austin homes for sale↵Search homes for sale↵Get pre-approved by a local lender↵Rolling Stone↵10 songs you didn't know were about drugs↵The 50 most anticipated movies of 2016↵30 nearly pornographic mainstream films↵'Saturday Night Live': All 141 cast members ranked↵45 most anticipated albums of 2016↵Food Network↵Big game sandwich recipes↵NFL-themed potato skins↵Where to get great doughnuts, from coast to coast↵Valentine's Day chocolate desserts↵Our best one-pot meals↵In case you missed it ↵↵What Playboy understands about nudity↵Man who walked on moon dies↵London's hidden train network↵What's in CIA's art collection?"
24: "Teen comes back to life during game↵Airline misplaces passengers↵Voice of Bugs Bunny, Daffy Duck dies↵Watch cute panda cub play outside for first time↵Air Force won't kill off Warthog↵Is F-35 fit for combat? Umm ..."
25: "'Resting bitch face' is real↵↵U.S."
26: "CRIME + JUSTICEENERGY + ENVIRONMENTEXTREME WEATHERSPACE + SCIENCE↵WORLD↵AFRICAAMERICASASIAEUROPEMIDDLE EAST↵POLITICS↵2016 ELECTIONWASHINGTONNATIONWORLD↵MONEY↵MARKETSTECHMEDIAPERSONAL FINANCELUXURY↵OPINION↵POLITICAL OP-EDSSOCIAL COMMENTARY↵HEALTH↵DIET + FITNESSLIVING WELLPARENTING + FAMILY↵ENTERTAINMENT↵CELEBRITY WATCHTV + WEBMOVIES + MUSIC↵TECH↵GADGETSCYBER SECURITYINNOVATION NATION↵STYLE↵FASHIONDESIGNARCHITECTUREAUTOSLUXURY↵TRAVEL↵BEST OF TRAVELSLEEPS + EATSBUSINESS TRAVELAVIATION + BEYOND↵SPORTS↵PRO FOOTBALLCOLLEGE FOOTBALLBASKETBALLBASEBALLSOCCER↵LIVING↵FOODRELATIONSHIPSRELIGION↵VIDEO↵LIVE TV DIGITAL STUDIOSCNN FILMSTV SCHEDULETV SHOWS A-Z↵MORE…↵PHOTOSLONGFORMINVESTIGATIONSIREPORTCNN PROFILESCNN LEADERSHIP↵U.S."
27: "Edition↵© 2016 Cable News Network. Turner Broadcasting System, Inc. All Rights Reserved."
length: 28
proto__: Array[0]

如何根据"↵"何时分割每个字符串?显示?

我尝试使用:

for (i in result1) {
    var res_split=result1[i].split("\n")
};

上述功能仅产生:

["Edition", "© 2016 Cable News Network. Turner Broadcasting System, Inc. All Rights Reserved."]

不是我想要的!

4 个答案:

答案 0 :(得分:1)

去寻找:

var result1 = ["string\nstring1"];

var res_split = [];
for (i in result1) {
  res_split.push(result1[i].split(/(\r\n|\n|\r)/gm));
}
console.log(res_split);

它尝试各种换行

答案 1 :(得分:0)

尝试

var res_split=[];

for(i in result1) { res_split.push(result1[i].split("\n"));  }

否则每次分配新值并更换旧值。

答案 2 :(得分:0)

您没有附加res_split数组。您将在每次迭代时替换它。请尝试以下方法:

var res_split = [];

for (var i in result1) {
    res_split.push(result1[i].split("\n"));
}

答案 3 :(得分:-1)

var res_split=[];
for (i in result1) {
    res_split.push(result1[i].split(/(\r\n|\n|\r)/gm));
};