2017-06-27 7 views

Antwort

4

Je nach Anwendungsfall können Sie versuchen const regex = /(\w+)/g;

Dies erfasst jedes Wort (das gleiche wie [a-zA-Z0-9_]) Zeichen einmal oder mehrmals. Dies setzt voraus, dass Sie Elemente in Ihrer durch Leerzeichen getrennten Zeichenfolge haben können, die mehr als ein Zeichen lang ist.

Hier ist ein Beispiel, das ich in regex101 gemacht:

const regex = /(\w+)/g; 
const str = `a b c d efg 17 q q q`; 
let m; 

while ((m = regex.exec(str)) !== null) { 
    // This is necessary to avoid infinite loops with zero-width matches 
    if (m.index === regex.lastIndex) { 
     regex.lastIndex++; 
    } 

    // The result can be accessed through the `m`-variable. 
    m.forEach((match, groupIndex) => { 
     console.log(`Found match, group ${groupIndex}: ${match}`); 
    }); 
} 
+1

Vielen Dank Kumpel. funktioniert –

5

Die String.split() unterstützt Regex als param;

String.prototype.split([separator[, limit]])

let str = 'a b c d e'; 
str.split(/ /); 
// [ 'a', 'b', 'c', 'd', 'e' ] 

let str = 'a01b02c03d04e'; 
str.split(/\d+/); 
// [ 'a', 'b', 'c', 'd', 'e' ] 
Verwandte Themen