Home > OS >  How could I split an array of words without using split() in javascript
How could I split an array of words without using split() in javascript

Time:11-02

I'm trying to figure out how to split words from a sentence in an array without using split() but using charAt() function.

function sentenceToWordArray(sentence) {
    let stringArray = [""]
    let j = 0
    
    for (let i = 0; i < sentence.length; i  ) {
        if (sentence.charAt(i) == " ") {
            j  ;
            stringArray.push("")
        
        } else {
            stringArray[j]  = sentence.charAt(i)
        }
    }
    return stringArray
}

Now I have the code working but I'm encountering some problems like for example "Hello World" turns into "Hello", "World" but if I add extra spaces for example " Hello World " it outputs ['', 'hello', '', 'there', '']. Is there a way to remove the extra spaces?

CodePudding user response:

If you just want to find all words in an input sentence, you may use match() and avoid splitting altogether:

var input = " Hello World ";
var words = input.match(/\w /g);
console.log(words);

CodePudding user response:

You can use trim() method, which trims the whitespaces from the start and end of a string

function sentenceToWordArray(sentence) {
    let stringArray = [""]
    let j = 0
    const trimedSentence = sentence.trim()
    for (let i = 0; i < trimedSentence.length; i  ) {
        if (trimedSentence.charAt(i) == " ") {
            j  ;
            stringArray.push("")
        
        } else {
            stringArray[j]  = trimedSentence.charAt(i)
        }
    }
    return stringArray
}

console.log(sentenceToWordArray('Hello, World'));
console.log(sentenceToWordArray('  Hello, World'));
console.log(sentenceToWordArray('Hello, World  '));

CodePudding user response:

Another quickfix:

function sentenceToWordArray(sentence) {
    let stringArray = [""]
    let j = 0
    
    for (let i = 0; i < sentence.length; i  ) {
        if (sentence.charAt(i) == " ") {
            j  ;
            stringArray.push("")
        
        } else {
            stringArray[j]  = sentence.charAt(i)
        }
    }
    return stringArray.filter(w => w.length > 0) // <-- I added this
}

CodePudding user response:

You're going to need something called a "state machine" (https://en.wikipedia.org/wiki/Finite-state_machine). Basically, you have a set of states your function is in. With each new input (=character), depending on the current state, the state is changed into another one, and some actions are performed as a side effect.

Example:

const STATE_BEGIN = 1   // no last character
const STATE_SPACE = 2   // the last character was a space
const STATE_NOSPACE = 3 // the last character was not a space

function split(text) {
    let state = STATE_BEGIN
    let words = []

    for (let char of text) {

        let isSpace = char === ' '

        switch (state) {
            case STATE_BEGIN:
            case STATE_SPACE:
                if (!isSpace) {
                    words.push(char)
                    state = STATE_NOSPACE
                } else {
                    state = STATE_SPACE
                }
                break;
            case STATE_NOSPACE:
                if (!isSpace) {
                    words[words.length - 1]  = char
                    state = STATE_NOSPACE
                } else {
                    state = STATE_SPACE
                }
                break;
        }
    }

    return words;
}

//

text = `       How razorback-jumping frogs     can level six piqued     gymnasts!`

console.log(split(text))

  • Related