Skip to content

Instantly share code, notes, and snippets.

@filipgorczynski
Last active August 29, 2015 14:13
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 filipgorczynski/81cb5b369939466ed3fd to your computer and use it in GitHub Desktop.
Save filipgorczynski/81cb5b369939466ed3fd to your computer and use it in GitHub Desktop.
(function () {
var koView = ko.views.manager.currentView.scimoz;
var currentPos = koView.currentPos;
try {
// Group operations into a single undo
koView.beginUndoAction();
// http://www.bennadel.com/blog/142-ask-ben-javascript-string-replace-method.htm
String.prototype.replaceAll = function(
strTarget, // The substring you want to replace
strSubString // The string you want to replace in.
) {
var strText = this;
var intIndexOfMatch = strText.indexOf(strTarget);
// Keep looping while an instance of the target string
// still exists in the string.
while (intIndexOfMatch != -1) {
// Relace out the current instance.
strText = strText.replace(strTarget, strSubString)
// Get the index of any next matching substring.
intIndexOfMatch = strText.indexOf(strTarget);
}
// Return the updated string with ALL the target strings
// replaced out with the new substring.
return strText;
};
var fixTrim = function(text) {
var lines = text.split(/\r\n|\n|\r/);
if (lines.length) {
var trimmed = [];
for (lineNumber in lines) {
trimmed.push(lines[lineNumber].replace(/^\s+/, '').replace(/\s+$/, ''));
}
return trimmed.join('\n');
}
return text;
}
// replace all multi occurence of white space with one space
var fixSpaces = function(text) {
return text.replace(/[\t ]+/gmi, ' ');
}
// remove unwanted characters
var fixCharacters = function(text) {
var chars = ['\u2020', '\u00A9', '\u002A', '\u00AE', '*', '\u2122', '\u2026', '\u2019' , '\u2014'];
for (idx in chars) {
text = text.replaceAll(chars[idx], '');
}
return text;
};
var fixUnit = function(text) {
return text.replace(/(\d+)[ \t]+(grams|g|mg|kg|ml|mcg)/gmi, '$1$2');
};
if (!!koView.selText) {
var newText = fixTrim(koView.selText);
newText = fixCharacters(newText);
newText = fixSpaces(newText);
newText = fixUnit(newText);
koView.replaceSel(newText);
};
} catch (e) {
alert(e);
}
finally {
// Must end undo action or may corrupt edit buffer
koView.endUndoAction();
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment