💾str.words()
JS ⟩ primitives ⟩ String ⟩ methods ⟩ .words()
generate words in a sentence. (returns a )
💾 replit:str.words()
// 🔸 str.words()
// generator of all "alphabetic words"
String.prototype.words = function*() {
// ⭐️ Unicode "alphabetic characters" between word boundaries
// ❗ Chinese and Japanese characters are NOT "alphabetic characters"
// ❗`\p` is not supported in Firefox yet❗
const word = /\b\p{Alphabetic}+\b/gu;
// ⭐️ (iterable) iterator of all matches (words)
const matches = this.matchAll(word);
// yield matched words
for (let match of matches) { yield match[0] }
};
💈範例:
// main
const text = `
This is a naïve test of the matchAll() method.
這裡中文字
✏️ うわ、喧嘩してる!何かあったんですか?
`;
// ⭐️ for-of loop
for (const word of text.words()) console.log(word);
// This
// is
// a
// naïve
// test
// of
// the
// matchAll
// method
// ⭐️ spread into array elements
[...text.words()]
// [
// 'This', 'is',
// 'a', 'naïve',
// 'test', 'of',
// 'the', 'matchAll',
// 'method'
// ]
String.prototype.split() - returns an array of strings (not efficient for very long strings)
str.slice2() - returns substring (support Unicode)
Last updated