Except link with Javascript - javascript

can you help me?
I'm trying to get this code below to make a excesão links in case the variable would be
var except_link = "blogspot.com, wordpress.com";
But it is only making excesão of 'blogspot.com'
thank you
var except_link = "blogspot.com, wordpress.com";
var allow_file = ".3gp,.7z,.aac,.ac3,.asf,.asx,.avi,.bzip,.divx,.doc,.exe,.flv,.jpg,.png,.gz,.gzip,.iso,.jar,.jav,.mid,.mkv,.mov,.mp3,.mp4,.mpeg,.mpg,.msi,.nrg,.ogg,.pdf,.ppt,.psd,.rar,.rm,.rmvb,.rtf,.swf,.tar,.tar.gz,.tgz,.torrent,.ttf,.txt,.wav,.wma,.wmv,.xls,.zip,180upload,1fichier,1filesharing,2shared,4files,4share,4shared,a2zupload,adf,adrive,adv,amazo,";
except_link = (link_except != null) ? link_except : except_link;
function check(siteurl) {
if ("" + allow_file != "undefined" && allow_file != "" && allow_file.replace(/\s/g, "") != "" && siteurl != "") {
if ((" " + allow_file).indexOf(",") > 0) {
pular = allow_file.split(",")
} else {
pular = new Array(allow_file)
}
for (s = 0; s < pular.length; s++) {
if ((" " + siteurl.toLowerCase()).indexOf(pular[s].toLowerCase()) > 0) {
if ("" + except_link != "undefined" && except_link != "" && except_link.replace(/\s/g, "") != "" && siteurl != "") {
if ((" " + except_link).indexOf(",") > 0) {
pular = except_link.split(",")
} else {
pular = new Array(except_link)
}
for (s = 0; s < pular.length; s++) {
if ((" " + siteurl.toLowerCase()).indexOf(pular[s].toLowerCase()) > 0) {
return false;
break
}
}
return true
} else {
return true
}
}
}
return false
} else {
return false
}
}

You're splitting based on "," where you are delimiting with ", " (comma followed by space). The problem could be that it doesn't match since the second URL in the split array will be " wordpress.com" (wordpress.com with a space in front of it).
To remedy this, you could either change your split function to split accordingly:
except_link = "blogspot.com, wordpress.com" // comma-space
...
except_link.split(", ") // comma-space
Or, change your input string to accommodate your split requirements:
except_link = "blogspot.com,wordpress.com" // comma, no space
...
except_link.split(",") // comma, no space

Related

How to replace "" to " by using JSON.Parser from scratch

I read an article about JSON.Parser from scratch by Tan Li Hau.
https://lihautan.com/json-parser-with-javascript/
And I want to custom his JSON.Parser which can replace "" to " or """ to ". I mean if " keep more than 1 continuously, replace to " .
ex)
'{"n": ""aaa, should, ""}'
to
'{"n": "aaa, should, "}'
But for now, there is a syntax error of course.
I found the parseString() loops while " comes next. So I tried to update parseString() to replace "" to " if it's continuously. But it's not working. Also It's not supported more than 1 ".
So if you could give me some advise, it would be helpful.
function fakeParseJSON(str) {
let i = 0;
const value = parseValue();
expectEndOfInput();
return value;
function parseObject() {
if (str[i] === "{") {
i++;
skipWhitespace();
const result = {};
let initial = true;
// if it is not '}',
// we take the path of string -> whitespace -> ':' -> value -> ...
while (i < str.length && str[i] !== "}") {
if (!initial) {
eatComma();
skipWhitespace();
}
const key = parseString();
if (key === undefined) {
expectObjectKey();
}
skipWhitespace();
eatColon();
const value = parseValue();
result[key] = value;
initial = false;
}
expectNotEndOfInput("}");
// move to the next character of '}'
i++;
return result;
}
}
function parseArray() {
if (str[i] === "[") {
i++;
skipWhitespace();
const result = [];
let initial = true;
while (i < str.length && str[i] !== "]") {
if (!initial) {
eatComma();
}
const value = parseValue();
result.push(value);
initial = false;
}
expectNotEndOfInput("]");
// move to the next character of ']'
i++;
return result;
}
}
function parseValue() {
skipWhitespace();
const value =
parseString() ??
parseNumber() ??
parseObject() ??
parseArray() ??
parseKeyword("true", true) ??
parseKeyword("false", false) ??
parseKeyword("null", null);
skipWhitespace();
return value;
}
function parseKeyword(name, value) {
if (str.slice(i, i + name.length) === name) {
i += name.length;
return value;
}
}
function skipWhitespace() {
while (
str[i] === " " ||
str[i] === "\n" ||
str[i] === "\t" ||
str[i] === "\r"
) {
i++;
}
}
function parseString() {
if (str[i] === '"') {
i++;
let result = "";
if (str[i - 1] + str[i] === '""') {
(str[i - 1] + str[i]).replace('""', '"');
}
while (i < str.length && str[i] !== '"') {
if (str[i] === "\\") {
const char = str[i + 1];
if (
char === '"' ||
char === "\\" ||
char === "/" ||
char === "b" ||
char === "f" ||
char === "n" ||
char === "r" ||
char === "t"
) {
result += char;
i++;
} else if (char === "u") {
if (
isHexadecimal(str[i + 2]) &&
isHexadecimal(str[i + 3]) &&
isHexadecimal(str[i + 4]) &&
isHexadecimal(str[i + 5])
) {
result += String.fromCharCode(
parseInt(str.slice(i + 2, i + 6), 16)
);
i += 5;
} else {
i += 2;
expectEscapeUnicode(result);
}
} else {
expectEscapeCharacter(result);
}
} else {
result += str[i];
}
i++;
}
expectNotEndOfInput('"');
i++;
return result;
}
}
function isHexadecimal(char) {
return (
(char >= "0" && char <= "9") ||
(char.toLowerCase() >= "a" && char.toLowerCase() <= "f")
);
}
function parseNumber() {
let start = i;
if (str[i] === "-") {
i++;
expectDigit(str.slice(start, i));
}
if (str[i] === "0") {
i++;
} else if (str[i] >= "1" && str[i] <= "9") {
i++;
while (str[i] >= "0" && str[i] <= "9") {
i++;
}
}
if (str[i] === ".") {
i++;
expectDigit(str.slice(start, i));
while (str[i] >= "0" && str[i] <= "9") {
i++;
}
}
if (str[i] === "e" || str[i] === "E") {
i++;
if (str[i] === "-" || str[i] === "+") {
i++;
}
expectDigit(str.slice(start, i));
while (str[i] >= "0" && str[i] <= "9") {
i++;
}
}
if (i > start) {
return Number(str.slice(start, i));
}
}
function eatComma() {
expectCharacter(",");
i++;
}
function eatColon() {
expectCharacter(":");
i++;
}
// error handling
function expectNotEndOfInput(expected) {
if (i === str.length) {
printCodeSnippet(`Expecting a \`${expected}\` here`);
throw new Error("JSON_ERROR_0001 Unexpected End of Input");
}
}
function expectEndOfInput() {
if (i < str.length) {
printCodeSnippet("Expecting to end here");
throw new Error("JSON_ERROR_0002 Expected End of Input");
}
}
function expectObjectKey() {
printCodeSnippet(`Expecting object key here
For example:
{ "foo": "bar" }
^^^^^`);
throw new Error("JSON_ERROR_0003 Expecting JSON Key");
}
function expectCharacter(expected) {
if (str[i] !== expected) {
printCodeSnippet(`Expecting a \`${expected}\` here`);
throw new Error("JSON_ERROR_0004 Unexpected token");
}
}
function expectDigit(numSoFar) {
if (!(str[i] >= "0" && str[i] <= "9")) {
printCodeSnippet(`JSON_ERROR_0005 Expecting a digit here
For example:
${numSoFar}5
${" ".repeat(numSoFar.length)}^`);
throw new Error("JSON_ERROR_0006 Expecting a digit");
}
}
function expectEscapeCharacter(strSoFar) {
printCodeSnippet(`JSON_ERROR_0007 Expecting escape character
For example:
"${strSoFar}\\n"
${" ".repeat(strSoFar.length + 1)}^^
List of escape characters are: \\", \\\\, \\/, \\b, \\f, \\n, \\r, \\t, \\u`);
throw new Error("JSON_ERROR_0008 Expecting an escape character");
}
function expectEscapeUnicode(strSoFar) {
printCodeSnippet(`Expect escape unicode
For example:
"${strSoFar}\\u0123
${" ".repeat(strSoFar.length + 1)}^^^^^^`);
throw new Error("JSON_ERROR_0009 Expecting an escape unicode");
}
function printCodeSnippet(message) {
const from = Math.max(0, i - 10);
const trimmed = from > 0;
const padding = (trimmed ? 4 : 0) + (i - from);
const snippet = [
(trimmed ? "... " : "") + str.slice(from, i + 1),
" ".repeat(padding) + "^",
" ".repeat(padding) + message
].join("\n");
console.log(snippet);
}
}
console.log(`${fakeParseJSON('{"n": ""string, should, ""}')}`);
https://codesandbox.io/embed/json-parser-with-error-handling-forked-9zetnc?fontsize=14&hidenavigation=1&theme=dark

convert a string containing boolean values to a boolean

If I have this ;
var a = "(true && false) && true && false"
And if I want to evaluate this string , what are the options ?
If I say, this code will be generated in the browser but there will be absolutely no user input in it , would it be safe to use eval ?
If not, what is the most performant way of parsing it ?
EDIt :
By the way, the string is dynamic , so I can't gaurantee that it's always like above , so it could be :
var a = "(true && false) || (true && (true && false)) && true && false"
FIY :
I know I can use eval, all I'm asking is, why I shouldn't use eval, or is there any other options?
EDIT : the original problem :
var a = function(){ return false} // all of them always return a boolean
var b = function(){ return true}
var c = function(){ return true}
var d = function(){ return false}
var conditions = "(a && b) && c && d"
I can't change the above code , I need to parse it, I need the condition to be evaluated ;
function ExecuteJavascriptString() {
var n = 0;
var s = "(true || false) || (true || (true || false)) && true";
var ifstate = " if (" + s + ") { console.log('done'); } ";
setTimeout(ifstate, 1);
}
ExecuteJavascriptString()
I was thinking maybe you can atleast verify that the string contains what you think it should contain, before running eval on it, using the RegExp /(?:(?:true)|(?:false)|(?:&&)|(?:\|\|)|[()\s])/g:
var validExp = "(true && false && true) || (true && (true && false)) && true";
var evilExp = "(true && false && true) || (true && (true && false)) && true function() { console.log('do evil stuff'); }";
console.log(evalBoolStr(validExp)); //false
console.log(evalBoolStr(evilExp)); //Invalid input
function evalBoolStr(str) {
if(str.match(/(?:(?:true)|(?:false)|(?:&&)|(?:\|\|)|[()\s])/g).join('') === str) {
return eval(str);
}
return 'Invalid input';
}
An attempt at actually writing a parser for boolean strings:
function parseBoolStr(str) {
var expressions = {};
var expressionRegex = new RegExp("\\((?:(?:!*true)|(?:!*false)|(?:&&)|(?:\\|\\|)|\\s|(?:!*\\w+))+\\)");
var expressionIndex = 0;
str = str.trim();
while (str.match(expressionRegex)) {
var match = str.match(expressionRegex)[0];
var expression = 'boolExpr' + expressionIndex;
str = str.replace(match, expression);
match = match.replace('(', '').replace(')', '');
expressions[expression] = match;
expressionIndex++;
}
return evalBoolStr(str, expressions);
}
function evalBoolStr(str, expressions) {
var conditions = str.split(' ');
if (conditions.length > 0) {
var validity = toBoolean(conditions[0], expressions);
for (var i = 1; i + 1 < conditions.length; i += 2) {
var comparer = conditions[i];
var value = toBoolean(conditions[i + 1], expressions);
switch (comparer) {
case '&&':
validity = validity && value;
break;
case '||':
validity = validity || value;
break;
}
}
return validity;
}
return 'Invalid input';
}
function toBoolean(str, expressions) {
var inversed = 0;
while (str.indexOf('!') === 0) {
str = str.replace('!', '');
inversed++;
}
var validity;
if (str.indexOf('boolExpr') === 0) {
validity = evalBoolStr(expressions[str], expressions);
} else if (str == 'true' || str == 'false') {
validity = str == 'true';
} else {
validity = window[str]();
}
for (var i = 0; i < inversed; i++) {
validity = !validity;
}
return validity;
}
var exp1 = "(true && true || false) && (true || (false && true))";
var exp2 = "(true && false) && true && false";
var exp3 = "(true && !false) && true && !false";
var exp4 = "(a && b) && c && d";
console.log(exp1 + ' = ' + parseBoolStr(exp1));
console.log(exp2 + ' = ' + parseBoolStr(exp2));
console.log(exp3 + ' = ' + parseBoolStr(exp3));
console.log(exp4 + ' = ' + parseBoolStr(exp4));
function parseBoolStr(str) {
var expressions = {};
var expressionRegex = new RegExp("\\((?:(?:!*true)|(?:!*false)|(?:&&)|(?:\\|\\|)|\\s|(?:!*\\w+))+\\)");
var expressionIndex = 0;
str = str.trim();
while (str.match(expressionRegex)) {
var match = str.match(expressionRegex)[0];
var expression = 'boolExpr' + expressionIndex;
str = str.replace(match, expression);
match = match.replace('(', '').replace(')', '');
expressions[expression] = match;
expressionIndex++;
}
return evalBoolStr(str, expressions);
}
function evalBoolStr(str, expressions) {
var conditions = str.split(' ');
if (conditions.length > 0) {
var validity = toBoolean(conditions[0], expressions);
for (var i = 1; i + 1 < conditions.length; i += 2) {
var comparer = conditions[i];
var value = toBoolean(conditions[i + 1], expressions);
switch (comparer) {
case '&&':
validity = validity && value;
break;
case '||':
validity = validity || value;
break;
}
}
return validity;
}
return 'Invalid input';
}
function toBoolean(str, expressions) {
var inversed = 0;
while (str.indexOf('!') === 0) {
str = str.replace('!', '');
inversed++;
}
var validity;
if (str.indexOf('boolExpr') === 0) {
validity = evalBoolStr(expressions[str], expressions);
} else if (str == 'true' || str == 'false') {
validity = str == 'true';
} else {
validity = window[str]();
}
for (var i = 0; i < inversed; i++) {
validity = !validity;
}
return validity;
}
function a() {
return false;
}
function b() {
return true;
}
function c() {
return true;
}
function d() {
return false;
}
Usage would then simply be parseBoolStr('true && false'); //false

What is the simplest way break text into single strings to be modified and joined again using JS?

For example, I am am working on a Pig Latin translator. I want a for loop to change the text to an array and allow the rest of my code to change single words and put it back together again as a result.
var pigLatinTranslator = function(firstWord) {
firstWord = firstWord.toLowerCase();
var splitText = firstWord.split(' ');
var finalResult = [];
for (var i = 0; i < splitText.length; i++) {
var singleWord = splitText[i];
if (singleWord.charAt(0) !== "a" && singleWord.charAt(0) !== "e" && singleWord.charAt(0) !== "i" && singleWord.charAt(0) !== "o" && singleWord.charAt(0) !== "u") {
var consonantsVar;
for (var i = 0; i < singleWord.length; i++) {
var chr = singleWord.charAt(i);
if ((chr === 'q') && (singleWord.charAt(i + 1) === 'u')) {
consonantsVar = (singleWord.slice(i + 2) + singleWord.slice(0, i) + "quay");
break;
} else if (chr === 'a' || chr === 'e' || chr === 'i' || chr === 'o' || chr === 'u') {
consonantsVar = (singleWord.slice(i) + singleWord.slice(0, i) + "ay");
break;
}
}
return consonantsVar;
}
else {
return (singleWord + "ay");
}
return splitText.join(' ');
}
};

How can I slice a block of text so that it doesn't end on a split word?

I've written code that takes a large block of text, splits it into 995 character blocks and pushes each block into an array. However, this often results splits words when they fall at the 995-character line- how could I edit my code so that each block of text is as close as possible to 995 characters long (must be under) but ends at the last available space?
function cutUp() {
var PAname = prompt("Determine PA type and PA Name (e.g. 5=mexican food=");
var chunks = [];
var OGstring = document.getElementById('PATypes').value;
var my_long_string = OGstring.split('1').join('').split('2').join('').split('3').join('').split('4').join('').split('5').join('').split('6').join('').split('7').join('').split('8').join('').split('9').join('').split('0').join('').split('[edit]').join('').split('[citation needed]').join('').split('[').join('').split(']').join('').split('(').join('').split(')').join('');
var i = 0;
var n = 0;
while (n < my_long_string.length) {
chunks.push(my_long_string.slice(n, n += 995));
}
if (chunks[0] != null) {
$('PAType=Name=Value8').innerHTML = PAname + chunks[0];
}
if (chunks[1] != null) {
$('PAType=Name=Value9').innerHTML = PAname + chunks[1];
}
if (chunks[2] != null) {
$('PAType=Name=Value10').innerHTML = PAname + chunks[2];
}
if (chunks[3] != null) {
$('PAType=Name=Value11').innerHTML = PAname + chunks[3];
}
if (chunks[4] != null) {
$('PAType=Name=Value12').innerHTML = PAname + chunks[4];
}
if (chunks[5] != null) {
$('PAType=Name=Value13').innerHTML = PAname + chunks[5];
}
if (chunks[6] != null) {
$('PAType=Name=Value14').innerHTML = PAname + chunks[6];
}
if (chunks[7] != null) {
$('PAType=Name=Value15').innerHTML = PAname + chunks[7];
}
if (chunks[8] != null) {
$('PAType=Name=Value16').innerHTML = PAname + chunks[8];
}
if (chunks[9] != null) {
$('PAType=Name=Value17').innerHTML = PAname + chunks[9];
}
////this is to create new exportable table
$('exportTable').innerHTML += $('tableContents').innerHTML;
$("exportTable").removeClass('hidden');
///this resets to default
defaultReset();
}​
Without any specific Javascript knowledge, I'd say to look ahead 995 characters, and if that character isn't itself a space, to start looking back towards the start until you find a space, and truncate there.
In C-like pseudocode, with chars being your big array of characters:
for(truncOffset = 995; truncOffset > 0; truncOffset--):
{
if chars[currentLoc + truncOffset] = ' ': /* a space character */ break;
}
Rinse, repeat to taste. Remember to move currentLoc to currentLoc + truncOffset after finding that space.

How to add a Visual Basic .NET syntax highlighting to CodeMirror editor?

How to add a Visual Basic .NET syntax highlighting to CodeMirror editor? Does exists the mode for this language on any library? What should I correct except keywords, blockKeywords and atoms?
Pascal example:
CodeMirror.defineMode("pascal", function(config) {
function words(str) {
var obj = {}, words = str.split(" ");
for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
return obj;
}
var keywords = words("and array begin case const div do downto else end file for forward integer " +
"boolean char function goto if in label mod nil not of or packed procedure " +
"program record repeat set string then to type until var while with");
var blockKeywords = words("case do else for if switch while struct then of");
var atoms = {"null": true};
var isOperatorChar = /[+\-*&%=<>!?|\/]/;
var curPunc;
function tokenBase(stream, state) {
var ch = stream.next();
if (ch == "#" && state.startOfLine) {
stream.skipToEnd();
return "meta";
}
if (ch == '"' || ch == "'") {
state.tokenize = tokenString(ch);
return state.tokenize(stream, state);
}
if (ch == "(" && stream.eat("*")) {
state.tokenize = tokenComment;
return tokenComment(stream, state);
}
if (/[\[\]{}\(\),;\:\.]/.test(ch)) {
curPunc = ch;
return null
}
if (/\d/.test(ch)) {
stream.eatWhile(/[\w\.]/);
return "number";
}
if (ch == "/") {
if (stream.eat("/")) {
stream.skipToEnd();
return "comment";
}
}
if (isOperatorChar.test(ch)) {
stream.eatWhile(isOperatorChar);
return "operator";
}
stream.eatWhile(/[\w\$_]/);
var cur = stream.current();
if (keywords.propertyIsEnumerable(cur)) {
if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement";
return "keyword";
}
if (atoms.propertyIsEnumerable(cur)) return "atom";
return "word";
}
function tokenString(quote) {
return function(stream, state) {
var escaped = false, next, end = false;
while ((next = stream.next()) != null) {
if (next == quote && !escaped) {end = true; break;}
escaped = !escaped && next == "\\";
}
if (end || !escaped) state.tokenize = null;
return "string";
};
}
function tokenComment(stream, state) {
var maybeEnd = false, ch;
while (ch = stream.next()) {
if (ch == ")" && maybeEnd) {
state.tokenize = null;
break;
}
maybeEnd = (ch == "*");
}
return "comment";
}
function Context(indented, column, type, align, prev) {
this.indented = indented;
this.column = column;
this.type = type;
this.align = align;
this.prev = prev;
}
function pushContext(state, col, type) {
return state.context = new Context(state.indented, col, type, null, state.context);
}
function popContext(state) {
var t = state.context.type;
if (t == ")" || t == "]" )
state.indented = state.context.indented;
return state.context = state.context.prev;
}
// Interface
return {
startState: function(basecolumn) {
return {
tokenize: null,
context: new Context((basecolumn || 0) - config.indentUnit, 0, "top", false),
indented: 0,
startOfLine: true
};
},
token: function(stream, state) {
var ctx = state.context;
if (stream.sol()) {
if (ctx.align == null) ctx.align = false;
state.indented = stream.indentation();
state.startOfLine = true;
}
if (stream.eatSpace()) return null;
curPunc = null;
var style = (state.tokenize || tokenBase)(stream, state);
if (style == "comment" || style == "meta") return style;
if (ctx.align == null) ctx.align = true;
if ((curPunc == ";" || curPunc == ":") && ctx.type == "statement") popContext(state);
else if (curPunc == "[") pushContext(state, stream.column(), "]");
else if (curPunc == "(") pushContext(state, stream.column(), ")");
else if (curPunc == ctx.type) popContext(state);
else if ( ctx.type == "top" || (ctx.type == "statement" && curPunc == "newstatement"))
pushContext(state, stream.column(), "statement");
state.startOfLine = false;
return style;
},
electricChars: "{}"
};
});
CodeMirror.defineMIME("text/x-pascal", "pascal");
Thanks for the help!
This worked for me -
I added this definition in clike mode js file
CodeMirror.defineMIME("text/x-vb", {
name: "clike",
keywords: words("AddHandler AddressOf Alias And AndAlso Ansi As Assembly Auto Boolean ByRef Byte " +
"ByVal Call Case Catch CBool CByte CChar CDate CDec CDbl Char CInt Class CLng CObj Const CShort CSng CStr CType " +
"Date Decimal Declare Default Delegate Dim DirectCast Do Double Each Else ElseIf End Enum Erase Error Event Exit False Finally "+
"For Friend Function Get GetType GoSub GoTo Handles If Implements Imports In Inherits Integer Interface Is " +
"Let Lib Like Long Loop Me Mod Module MustInherit MustOverride MyBase MyClass Namespace New Next Not "+
"Nothing NotInheritable NotOverridable Object On Option Optional Or OrElse Overloads Overridable Overrides " +
"ParamArray Preserve Private Property Protected Public RaiseEvent ReadOnly ReDim REM RemoveHandler Resume " +
"Return Select Set Shadows Shared Short Single Static Step Stop String Structure Sub SyncLock Then Throw " +
"To True Try TypeOf Unicode Until Variant When While With WithEvents WriteOnly Xor"),
//blockKeywords: words("catch class do else finally for if switch try while"),
atoms: words("True False Null"),
hooks: {
"#": function(stream, state) {
stream.eatWhile(/[\w\$_]/);
return "meta";
}
}
});

Categories

Resources