Last active
May 22, 2018 16:22
-
-
Save jorgeortega/680660f618d57066846ad010d243123b to your computer and use it in GitHub Desktop.
Split html string in parts by tag
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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