diff options
author | Joel Kronqvist <joel.h.kronqvist@gmail.com> | 2022-02-09 22:24:26 +0200 |
---|---|---|
committer | Joel Kronqvist <joel.h.kronqvist@gmail.com> | 2022-02-09 22:24:26 +0200 |
commit | b270c4475ca6ed61784ed8368ab42fea3dc528e5 (patch) | |
tree | 2b895a8b5d7b0a8ed0c8eea37278e3ab10e048ba /Functions/stringFuncs.js | |
parent | 41b36e79f32e6a9efffe1c0100ddc339dbaaeabb (diff) | |
download | LYLLRuoka-b270c4475ca6ed61784ed8368ab42fea3dc528e5.tar.gz LYLLRuoka-b270c4475ca6ed61784ed8368ab42fea3dc528e5.zip |
Merged all functions from the JoelHMikael/funcs
Necessary, because we don't want to complicate our update script & its anyways better like this. They weren't any complicated functions.
Diffstat (limited to 'Functions/stringFuncs.js')
-rw-r--r-- | Functions/stringFuncs.js | 51 |
1 files changed, 51 insertions, 0 deletions
diff --git a/Functions/stringFuncs.js b/Functions/stringFuncs.js new file mode 100644 index 0000000..8dddc75 --- /dev/null +++ b/Functions/stringFuncs.js @@ -0,0 +1,51 @@ +function replaceElement(source, element, value) { + const firstTag = `<${element}>`; + + const firstSpace = element.indexOf(" "); + if (firstSpace !== -1) + element = element.substring(0, firstSpace); + const startTag = `<${element}.*?>`; + const endTag = `</${element}.*?>`; + + const span = getTagSpan(source, [startTag, endTag], firstTag); + + return source.substring(0, span[0]) + + value + + source.substring(span[1]); +} + +function getTagSpan(s, tags=["\\(", "\\)"], customFirstTag=undefined) +{ + customFirstTag = new RegExp(customFirstTag || tags[0]); + let i = s.search(customFirstTag); + if (i === -1) + return s; + + tags = [ + new RegExp("^" + tags[0]), + new RegExp("^" + tags[1]) + ]; + + const start = i; + i++; + let depth = 1; + while((depth !== 0) && (i !== s.length)) + { + let maybeStartTag = s.substring(i); + let maybeEndTag = s.substring(i); + + depth += +tags[0].test(maybeStartTag) + -tags[1].test(maybeEndTag); + + i++; + } + + i += (s.substring(i - 1).match(tags[1]) || [""])[0] .length - 1; + return [start, i]; +} + +const countOccurrences = (s, regex) => (s.match(regex) || []).length; +module.exports = { + span: getTagSpan, + replaceElement: replaceElement, + count: countOccurrences +}
\ No newline at end of file |