How to split a string into words in JavaScript

2 Answers

0 votes
function splitString(s, delims) {
    // Build a RegExp from the delimiter pattern
    const re = new RegExp(delims);

    // Split using regex, filter empty tokens
    return s.split(re).filter(t => t.length > 0);
}

const s = '-c, c++.. c#:: -java ,php...python      go';
const delims = "[ ,.:\\-!]+";

const tokens = splitString(s, delims);

for (const t of tokens) {
    console.log(t);
}


/*
run:

c
c++
c#
java
php
python
go

*/

 



answered Aug 29 by avibootz
0 votes
function splitString(s, delims) {
    const delimSet = new Set(delims.split(""));

    let normalized = "";
    for (const ch of s) {
        normalized += delimSet.has(ch) ? " " : ch;
    }

    return normalized.split(" ").filter(t => t.length > 0);
}

const s = "-c, c++.. c#:: -java! ,php...python:      go!";
const delims = " ,.:\\-!";

const tokens = splitString(s, delims);

for (const t of tokens) {
    console.log(t);
}


/*
run:

c
c++
c#
java
php
python
go

*/

 



answered Aug 29 by avibootz
...