Splitting a string into an array while ignoring content between apostrophes

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 .... )

+6
source share
1 answer

You can try combining instead of splitting:

 string.match(/(?:['"].+?['"])|\S+/g) 

The above regex will match any conclusion between quotation marks (including quotation marks) or anything that is not a space.

If you also want to match characters after quotes, for example ? and ! , you can try:

 /(?:['"].+?['"]\W?)|\S+/g 

For "hello 'every body'!" he will give you this array:

 ["hello", "'every body'!"] 

Note that \W also matches a space, if you want to combine punctuation, you can be explicit using a character class instead of \W

 [,.?!] 

Or just trim the lines after matching:

 string.match(regex).map(function(x){return x.trim()}) 
+3
source

Source: https://habr.com/ru/post/973619/


All Articles