I need something that takes a string and divides it into an array. I want to break it after each space, so this is -
"Welcome all!" turns into ---> ["Hello," "Everything!" ]
However, I want him to ignore the spaces between the apostrophes. So for examples -
"How are you today?" turns into ---> ["How", "you are", "today?" ]
Now I have written the following code (which works), but something tells me that what I did is pretty terrible, and that this can be done, probably 50% less than the code. I'm also quite new to JS, so I think I still don't stick with all the idioms of the language.
function getFixedArray(text) { var textArray = text.split(' '); //Create an array from the string, splitting by spaces. var finalArray = []; var bFoundLeadingApostrophe = false; var bFoundTrailingApostrophe = false; var leadingRegExp = /^'/; var trailingRegExp = /'$/; var concatenatedString = ""; for (var i = 0; i < textArray.length; i++) { var text = textArray[i]; //Found a leading apostrophe if(leadingRegExp.test(text) && !bFoundLeadingApostrophe && !trailingRegExp.test(text)) { concatenatedString =concatenatedString + text; bFoundLeadingApostrophe = true; } //Found the trailing apostrophe else if(trailingRegExp.test(text ) && !bFoundTrailingApostrophe) { concatenatedString = concatenatedString + ' ' + text; finalArray.push(concatenatedString); concatenatedString = ""; bFoundLeadingApostrophe = false; bFoundTrailingApostrophe = false; } //Found no trailing apostrophe even though the leading flag indicates true, so we want this string. else if (bFoundLeadingApostrophe && !bFoundTrailingApostrophe) { concatenatedString = concatenatedString + ' ' + text; } //Regular text else { finalArray.push(text); } } return finalArray; }
I would be deeply grateful if someone could get through this and teach me how to rewrite it in a more correct and efficient way (and, possibly, more "JS").
Thanks!
Edit -
Well, I just found a few problems, some of which I fixed, and some of them Iām not sure how to handle without making this code too complicated (for example, the string "hello" to every body! " Does not split correctly .... )
source share