I came here with an approach that could parse the string for quotes and quotes, keep the order of quotes and not quotes, and then output them using specific tags wrapped around them for React or React Native, so I didn't use the answers here, because that I was not sure how to make them fit my needs, and then did it.
function parseQuotes(str) {
var openQuote = false;
var parsed = [];
var quote = '';
var text = '';
var openQuote = false;
for (var i = 0; i < str.length; i++) {
var item = str[i];
if (item === '"' && !openQuote) {
openQuote = true;
parsed.push({ type: 'text', value: text });
text = '';
}
else if (item === '"' && openQuote) {
openQuote = false;
parsed.push({ type: 'quote', value: quote });
quote = '';
}
else if (openQuote) quote += item;
else text += item;
}
if (openQuote) parsed.push({ type: 'text', value: '"' + quote });
else parsed.push({ type: 'text', value: text });
return parsed;
}
What about this:
'Testing this "shhhh" if it "works!" " hahahah!'
produces the following:
[
{
"type": "text",
"value": "Testing this "
},
{
"type": "quote",
"value": "shhhh"
},
{
"type": "text",
"value": " if it "
},
{
"type": "quote",
"value": "works!"
},
{
"type": "text",
"value": " "
},
{
"type": "text",
"value": "\" hahahah!"
}
]
which makes it easy to wrap tags around it depending on what it is.
https://jsfiddle.net/o6seau4e/4/
source
share