Skip to content

Instantly share code, notes, and snippets.

@jorgeortega
Last active May 22, 2018 16:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jorgeortega/680660f618d57066846ad010d243123b to your computer and use it in GitHub Desktop.
Save jorgeortega/680660f618d57066846ad010d243123b to your computer and use it in GitHub Desktop.
Split html string in parts by tag
/**
* Splits a string in half by tag name
* i.e. '<p>' or 'p'
* returns array of 2 strings
*
*/
export const splitTextByTag = (text, tag) => {
let closingTag = '';
// clean text from line breaks
let cleanText = text.replace(/\r?\n|\r/g, '');
let resultArray = [];
// Add openning bracket if not specified
if (tag.indexOf('<') === -1) {
closingTag = '<';
}
// Add closing slash if not specified
if (tag.indexOf('/') === -1) {
// case when specifying tag without slash i.e. <p>
if (tag.indexOf('<') !== -1) {
closingTag = ['</', tag.slice(1)].join('');
} else {
closingTag += '/';
}
}
// Add closing bracket if not specified
if (tag.indexOf('>') === -1) {
closingTag += tag + '>';
}
// Split by closing tag
let splittedArray = cleanText && cleanText.split(closingTag);
// Remove empty elements
splittedArray = splittedArray.filter((text) => text.length)
// add back tag removed by split
splittedArray = splittedArray.map((text) => text + closingTag);
// get first block of text
resultArray[0] = splittedArray[0]
// join the rest if any
if (splittedArray.length > 1) {
splittedArray.shift()
resultArray[1] = splittedArray.join('')
}
return resultArray;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment