Javascript: Syntax error, unrecognized expression: <h1> - javascript

EDITING to include solution based on Brian Hedlund's suggestion. Solution is at bottom.
I am getting this error in the console log
Syntax error, unrecognized expression: <h1>
This is the line generating the error
var substring = txt.find(tag).eq(i).text();
Sample data and code are below.
Why does that line throw that error and how can it be fixed?
I have verified that the function _mpactIdeation_countOccurrences() does execute properly as well as all lines in the function mpactIdeation_getTagContentsKeyphrase() above the line
var substring = txt.find(tag).eq(i).text();
Thanks for your time and consideration,
Tim
Sample Data:
The variable tag holds "<h1>".
The variable kp holds "fish".
The variable txt holds "<p>one.</p><h1>fish</h1><p>two fish. red fish. blue fish.</p>".
Code:
this.mpactIdeation_getTagContentsKeyphrase = function( tag, kp ) {
try {
var result = 0;
var num = 0;
var txt = this.oText;
var tagcount = this._mpactIdeation_countOccurrences( txt, tag, false );
txt = jQuery(txt);
for (i = 0; i < tagcount; i++) {
tag = this._mpactIdeation_escapeRegExp(tag);
var substring = txt.find(tag).eq(i).text();
result += this._mpactIdeation_countOccurrences(substring, kp, false);
}
return num;
} catch(e) {
console.log(e);
return false;
}
}
this._mpactIdeation_countOccurrences = function( string, subString, allowOverlapping ) {
try {
string += "";
subString += "";
if (subString.length <= 0) return (string.length + 1);
var num = 0,
pos = 0,
step = allowOverlapping ? 1 : subString.length;
while (true) {
pos = string.indexOf(subString, pos);
if (pos >= 0) {
++num;
pos += step;
} else break;
}
return num;
} catch(e) {
console.log(e);
return false;
}
}
SOLUTION:
this.mpactIdeation_getTagContentsKeyphrase = function( tag, kp ) {
try {
var result = 0;
var num = 0;
var txt = this.oText;
var tagcount = this._mpactIdeation_countOccurrences( txt, tag, false );
txt = jQuery(txt);
tag = this._mpactIdeation_tagToText(tag);
for (i = 0; i < tagcount; i++) {
var substring = txt.find(tag).eq(i).text();
result += this._mpactIdeation_countOccurrences(substring, kp, false);
}
return num;
} catch(e) {
console.log(e);
return false;
}
}
this._mpactIdeation_countOccurrences = function( string, subString, allowOverlapping ) {
try {
string += "";
subString += "";
if (subString.length <= 0) return (string.length + 1);
var num = 0,
pos = 0,
step = allowOverlapping ? 1 : subString.length;
while (true) {
pos = string.indexOf(subString, pos);
if (pos >= 0) {
++num;
console.log( "countOccurrences FOUND: " + subString + " INCREMENT");
pos += step;
} else break;
}
return num;
} catch(e) {
console.log(e);
return false;
}
}
this._mpactIdeation_tagToText = function(tag) {
try {
return tag = tag.replace(/[<>]/g, '');
} catch(e) {
console.log(e);
return false;
}
}

The correct find syntax is find('h1'), not find('<h1>')
This will fix your error, but not find your h1. find looks for descendants of the searched target, and since your txt has no root node, the intended target h1 is not a descendant, but a sibling. .siblings('h1') would do the trick.

Related

isset equivalent in javascript to find palindrome

I created a script in PHP to find a palindrome, but when I try to do the same in JavaScript, then it is not working as expected. It's not just a matter of checking if the string that is reversed matches, but any order of the string has to be checked as well.
In other words, "mom" should return as true, "mmo" should return as true, "omm" should return as true, etc..., which is what the PHP script does, but the JS script below doesn't even work for the first iteration for the string "mom"
The following is the PHP script:
<?php
function is_palindrom($str) {
$str_array = str_split($str);
$count = array();
foreach ($str_array as $key) {
if(isset($count[$key])) {
$count[$key]++;
} else {
$count[$key] = 1;
}
}
$odd_counter = 0;
foreach ($count as $key => $val) {
if(($val % 2) == 1) {
$odd_counter++;
}
}
return $odd_counter <= 1;
}
echo is_palindrom('mom') ? "true" : "false";
The following is what I have tried in JS:
var count = [];
var strArr = [];
var oddCounter = 0;
var foreach_1 = function(item, index) {
console.log("count[index]: " + count[index]);
if (typeof count[index] !== "undefined") {
count[index]++;
} else {
count[index] = 1;
}
};
var foreach_2 = function(item, index) {
console.log("item: " + item + " item % 2: " + eval(item % 2));
if (eval(item % 2) == 1) {
oddCounter++;
}
console.log("oddCounter: " + oddCounter);
return oddCounter <= 1;
};
var isPalindrom = function(str) {
strArr = str.split("");
console.log(strArr);
strArr.forEach(foreach_1);
console.log(count);
count.forEach(foreach_2);
};
I believe it is failing where I try to replicate isset in javascript, with the following code:
if (typeof count[index] !== "undefined") {
As a result, I have tried to write my own isset function, but still the same result, it is not working:
var isset = function(obj) {
if (typeof obj === "undefined" || obj === null) {
return false;
} else {
return true;
}
};
With the following function being called:
if (isset(count[index])) {
count[index]++;
} else {
count[index] = 1;
}
As usual, any help would be appreciated and thanks in advance
BTW, it's killing me that I cannot remember the word for several revisions or iterations of something - I know that it starts with "re"
My attempt:
let p1 = `No 'x' in Nixon.`
let p2 = `Was it a car or a cat I saw?`
let p3 = `A man, a plan, a canal, Panama!`
function is_palindrome (str) {
const normalize = str => str.replace(/[.,:;`'"!?\/#$%\^&\*{}=\-_~()\s]/g, '').toLowerCase()
const reverse = str => [...str].reverse().join('')
return normalize(str) === reverse(normalize(str))
? true
: false
}
console.log(is_palindrome(p1))
console.log(is_palindrome(p2))
console.log(is_palindrome(p3))
First, thank you for all the comments.
Second, I ran a var_dump on the count array in the PHP file and this was the result:
array (size=2)
'm' => int 2
'o' => int 1
Which lead me to understand that count in js has to be an object for this work and I would have to create indexes of the object, depending on the string entered.
One thing lead to another and a complete re-write, but it works, along with a spell checker - see link at the bottom for complete code:
var count = {};
var strArr = [];
var oddCounter = 0;
var objKeys = [];
var splitString;
var reverseArray;
var joinArray;
var url = "test-spelling.php";
var someRes = "";
var mForN = function(obj, strArr) {
for (var y = 0; y < strArr.length; y++) {
// console.log("obj[strArr[" + y + "]]: " + obj[strArr[y]]);
if (isset(obj[strArr[y]])) {
obj[strArr[y]]++;
} else {
obj[strArr[y]] = 1;
}
}
return obj;
};
var mForN_2 = function(obj, objKeys) {
for (var z = 0; z < objKeys.length; z++) {
/* console.log(
"obj[objKeys[z]]: " +
obj[objKeys[z]] +
" obj[objKeys[z]] % 2: " +
eval(obj[objKeys[z]] % 2)
); */
if (eval(obj[objKeys[z]] % 2) == 1) {
oddCounter++;
}
// console.log("oddCounter: " + oddCounter);
}
return oddCounter <= 1;
};
var isset = function(obj) {
if (typeof obj === "undefined" || obj === null) {
return false;
} else {
return true;
}
};
var isPalindrom = function(str) {
// reverse original string
splitString = str.split("");
reverseArray = splitString.reverse();
joinArray = reverseArray.join("");
var checking = checkSpellingOfStr(str);
if (str == joinArray) {
strArr = str.split("");
// console.log("strArr: " + strArr);
objKeys = makeObjKeys(count, strArr);
// console.log("filled count before mForN: " + JSON.stringify(count));
// create array of keys in the count object
objKeys = Object.keys(count);
// console.log("objKeys: " + objKeys);
count = mForN(count, strArr);
// console.log("count after mForN: " + JSON.stringify(count));
return mForN_2(count, objKeys);
} else {
return 0;
}
};
var makeObjKeys = function(obj, arr) {
for (var x = 0; x < arr.length; x++) {
obj[arr[x]] = null;
}
return obj;
};
var checkSpellingOfStr = function(someStr) {
var formData = {
someWord: someStr
};
$.ajax({
type: "GET",
url: url,
data: formData,
success: function(result) {
if (!$.trim(result)) {
} else {
console.log(result);
$("#checkSpelling").html(result);
}
}
});
};
Start everything with the following call:
isPalindrom("mom") ? demoP.innerHTML = "is pal" : demoP.innerHTML = "is not pal";
In my example, I have a form and I listen for a button click as follows:
var palindromeTxt = document.getElementById("palindromeTxt").value;
var btn = document.getElementById("button");
btn.addEventListener("click", function (event) {
isPalindrom(palindromeTxt) ? demoP.innerHTML = "is pal" : demoP.innerHTML = "is not pal";
});
The following is the php for spell check:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
if(!empty($_REQUEST['someWord']))
{
$someWord = $_REQUEST['someWord'];
}
$pspell_link = pspell_new("en");
if (pspell_check($pspell_link, $someWord)) {
echo trim($someWord) . " is a recognized word in the English language";
} else {
echo "Your word is either misspelled or that is not a recognized word";
}
You will need pspell installed on your server, as well as adding extension=pspell.so to your php.ini
This is what I did, to get it running locally on my mac:
cd /Users/username/Downloads/php-5.6.2/ext/pspell
/usr/local/bin/phpize
./configure --with-php-config=/usr/local/php5-5.6.2-20141102-094039/bin/php-config --with-pspell=/opt/local/
make
cp ./modules/* /usr/local/php5-5.6.2-20141102-094039/lib/php/extensions/no-debug-non-zts-20131226
sudo apachectl restart
check your phpinfo file and you should see the following:
pspell
PSpell Support enabled
Live example

creating a new array out of an object

I've created a JavaScript object to get the number of times a character repeats in a string:
function getFrequency(string) {
// var newValsArray =[];
var freq = {};
for (var i=0; i<string.length;i++) {
var character = string.charAt(i);
if (freq[character]) {
freq[character]++;
} else {
freq[character] = 1;
}
}
return freq;
}
Now, I'm trying to construct a new string composed of the keys & their properties (the letters) & numbers of times the letters repeat if the number (property) is more than one but I keep getting undefined and I don't know why:
function newString(freq){
var newValsArray = [];
for (var prop in freq) {
if (freq[prop]>1){
newValsArray.push(prop + freq[prop]);
}
else if (freq[prop] < 2){
newValsArray.push(prop);
}
}
return newValsArray;
}
I feel like my syntax is off or something... if anyone has any suggestions, I'd really appreciate it...
You aren't explicitly returning anything from newString(), so it will return undefined. It sounds like you want something like this:
return newValsArray.join('');
at the end of newString() to construct an actual string (instead of returning an array). With that change, newString(getFrequency("Hello there") will return 'He3l2o thr'.
function getFrequency(string) {
// var newValsArray =[];
var freq = {};
for (var i = 0; i < string.length; i++) {
var character = string.charAt(i);
if (freq[character]) {
freq[character] ++;
} else {
freq[character] = 1;
}
}
return freq;
}
function newString(freq) {
var newValsArray = [];
for (var prop in freq) {
if (freq[prop] > 1) {
newValsArray.push(prop + freq[prop]);
} else if (freq[prop] < 2) {
newValsArray.push(prop);
}
}
return newValsArray.join("");
}
var mystring = "Here are some letters to see if we have any freq matches and so on.";
var results = newString(getFrequency(mystring));
var elem = document.getElementById("results");
elem.innerHTML = results;
<div id="results"></div>
You are not returning anything from the newString function. Add return newString; as the last line of the newString function. Adding that line does result in something being returned, though I can't tell if it is what you expected.
var text = "asdfjhwqe fj asdj qwe hlsad f jasdfj asdf alhwe sajfdhsadfjhwejr";
var myFreq = getFrequency(text);
show(myFreq);
var myNewValsArray = newString(myFreq);
show(myNewValsArray);
function getFrequency(string) {
// var newValsArray =[];
var freq = {};
for (var i=0; i<string.length;i++) {
var character = string.charAt(i);
if (freq[character]) {
freq[character]++;
} else {
freq[character] = 1;
}
}
return freq;
}
function newString(freq){
var newValsArray = [];
for (var prop in freq) {
if (freq[prop]>1){
newValsArray.push(prop + freq[prop]);
}
else if (freq[prop] < 2){
newValsArray.push(prop);
}
}
return newValsArray; // ******** ADD THIS LINE
}
function show(msg) {
document.write("<pre>" + JSON.stringify(msg, null, 2) + "</pre>");
}

How to write a javascript function that checks if first and last characters in a string are equal

I been doing this javascript challenge and I'm pretty close, but something is off.Here's the challenge:
Given an array of strings containing three types of braces: round (), square [] and curly {}
Your task is to write a function that checks whether the braces in each string are correctly matched. Prints 1 to standard output (console.log) if the braces in each string are matched and 0 if they're not (one result per line)
my code is this:
var infoToParse = [ ")(){}", "[]({})", "([])", "{()[]}", "([)]" ];
function checkBraces(infoToParse) {
var tabChars = infoToParse;
for (i= 0; tabChars.length - 1; i+=1) {
if (tabChars[i].charAt(0) === tabChars[i].charAt(tabChars[i].length-1)){
console.log(1);
}else{
console.log(0);
}
}
}
checkBraces(infoToParse);
The output with the current array items should be Output:
0
1
1
1
0
As pointed out in the comment, only having the first and the last character same would not result in a correct solution.
You can try the following technique:
Maintain a stack, each time you encounter an opening bracket i.e round "(", square "[" or curly "{"; push this into stack. Now whenever you encounter a closing bracket, pop an element from the stack. If these two match i.e both are of same type, then carry on till stack and string both are empty. If at any point these don't match then break and return false.
I'll write a code for it and post it soon.
I guess you could do it in this way, keeping a "tree" of starting positions. Didn't test any other testcases than your own though :)
var testCases = [")(){}", "[]({})", "([])", "{()[]}", "([)]"];
var braceType = {
round: ["(", ")"],
curly: ["{", "}"],
square: ["[", "]"]
};
var bracePosition = {
start: ["{", "(", "["],
end: ["}", ")", "]"]
};
function typeOfBraces(sign) {
for (var property in braceType) {
if (braceType[property].indexOf(sign) < 0) {
continue;
}
if (bracePosition.start.indexOf(sign) < 0) {
return {
type: property,
position: "end"
};
} else {
return {
type: property,
position: "start"
};
}
}
throw "Sign is not a brace!";
};
function Braces(brace, parent, type) {
this.brace = brace;
this.parent = parent || null;
this.type = type || {
type: 'init',
position: ''
};
this.children = [];
this.nextBrace = function(nextSign) {
var nextType = typeOfBraces(nextSign);
if (nextType.position === 'start') {
var child = new Braces(nextSign, this, nextType);
this.children.push(child);
return child;
}
if (nextType.position === 'end') {
if (this.type.position === '') {
throw 'Cannot start with an end tag!';
}
if (this.type.position === 'end' && this.parent === null) {
throw 'Cannot end the sequence';
}
if (this.type.position === 'end' && this.parent.position === 'start') {
if (this.type.type === this.parent.type) {
var child = new Braces(nextSign, this.parent, nextType);
this.parent.children.add(child);
return this.parent;
}
}
}
if (this.type.position === 'start' && nextType.type === this.type.type && nextType.position === 'end') {
return this.parent;
}
return new Braces(nextSign, this, nextType);
};
}
for (var i = 0; i < testCases.length; i++) {
var brace = new Braces(testCases[i]);
for (var j = 0, len = testCases[i].length; j < len; j++) {
try {
brace = brace.nextBrace(testCases[i][j]);
} catch (e) {
console.log(e);
brace = null;
break;
}
}
if (brace != null && brace.parent == null) {
// valid entry
console.log(brace);
console.log(testCases[i] + " is a valid sequence");
} else {
// invalid entry
console.log(testCases[i] + " is an invalid sequence");
}
}
or, to make it a bit easier and to check check the brackets:
function validBraces(braceSequence) {
var stack = '',
i, len, lastStack = -1,
toAdd = "{([",
toRemove = "})]",
sign;
for (i = 0, len = braceSequence.length; i < len; i++) {
sign = braceSequence[i];
if (toAdd.indexOf(sign) >= 0) {
stack += sign;
lastStack++;
} else if (toRemove.indexOf(sign) >= 0) {
if (toAdd.indexOf(stack.charAt(lastStack)) !== toRemove.indexOf(sign)) {
// format exception
console.warn('Format exception, didn\'t expect ' + sign + ' (current stack: ' + stack + ')');
return false;
} else {
stack = stack.slice(0, -1);
lastStack--;
}
} else {
console.warn('Invalid character exception, didn\'t expect ' + sign + ' (current stack: ' + stack + ')');
return false;
}
}
return true;
}
var testCases = [")(){}", "[]({})", "([])", "{()[]}", "([)]"];
for (var i = 0; i < testCases.length; i++) {
if (validBraces(testCases[i])) {
console.log(testCases[i] + ' is a valid sequence');
} else {
console.log(testCases[i] + ' is an invalid sequence');
}
}
If you can use Regular Expressions, you can really slim it down:
var stringArray = [ ")(){}", "[]({})", "([])", "{()[]}", "([)]" ];
function checkBraces(infoToParse) {
for (i = 0; i < infoToParse.length; i += 1) {
var regX = /^\[.*\]$|^\{.*\}$|^\(.*\)$/gi;
var str = infoToParse[i];
console.log(str.match(regX) ? 1 : 0);
}
}
checkBraces(stringArray);
Also, as I stated in my comment, your for syntax was off. Oh, and instead of i+=1, you can use i++ to simplify it.

What's wrong in my JS function?

I am optimizing a Java code to JS, but runs on Nashorn and do not own debug option. The input is val = "JPG ou PNG" and the output is "JPG ou PNG". Why does this happen? I need the output to be "jpg/png"
Function
function process(val) {
var cleaned = val.replaceAll("[•×\\tª°▪º⊗ fi ²●˚~ĩ`ũ]", "").trim().toLowerCase();
var out = [];
if (cleaned.contains("ou")) {
out = cleaned.split("ou");
}
else if (cleaned.contains("/")) {
out = cleaned.split("/");
}
else {
return cleaned;
}
for (var i = 0; i < out.length; i++) {
out[i] = out[i].trim();
}
return join(out, "/");
}
Three of your functions don't exist in javascript:
replaceAll(searchValue, newValue) in javascript is replace(searchValue, newValue)
contains(searchValue) in javascript is indexOf(searchValue) > -1
join(array, separator) in javascript is array.join(separator)
JSFIDDLE DEMO
Here's my solution:
function process(val) {
var cleaned = val.replace("[•×\\tª°▪º⊗ fi ²●˚~ĩ`ũ]", "").trim().toLowerCase();
var out = [];
if (cleaned.indexOf("ou") >= 0) {
out = cleaned.split("ou");
}
else if (cleaned.indexOf("/") >= 0) {
out = cleaned.split("/");
}
else {
return cleaned;
}
for (var i = 0; i < out.length; i++) {
out[i] = out[i].trim();
}
return join(out, "/");
}
Your logic was right, but strings in Javascript don't have 'replaceAll' and 'contains', so I replaced them with 'replace' and 'indexOf(x) >= 0'.
Also, you mentioned you don't have the option to debug in your environment, yet the function you provided is pretty standalone. This means you could easily copy it into another environment to test it in isolation.
For example, I was able to wrap this code in a HTML file then open it in my web browser (I had to implement my own 'join').
<html>
<body>
<script>
function join(val, divider) {
var out = "";
for(var i = 0; i < val.length; i++) {
if(out.length > 0) out += divider;
out += val[i];
}
return out;
}
function process(val) {
var cleaned = val.replace("[•×\\tª°▪º⊗ fi ²●˚~ĩ`ũ]", "").trim().toLowerCase();
var out = [];
if (cleaned.indexOf("ou") >= 0) {
out = cleaned.split("ou");
}
else if (cleaned.indexOf("/") >= 0) {
out = cleaned.split("/");
}
else {
return cleaned;
}
for (var i = 0; i < out.length; i++) {
out[i] = out[i].trim();
}
return join(out, "/");
}
var inval = "JPG ou PNG";
var outval = process(inval);
console.log(inval + " => " + outval);
</script>
</body>
</html>
I verified it works by opening up the console and seeing the output "JPG ou PNG => jpg/png".

Checking value in textbox against an array script not working

I have a script that I am checking values from textbox against an array, the array are all values from a drop down list. Cant seem to get it to work. Thanks.
<script type = "text/javascript">
function chkName() {
var ddlArray = new Array();
var ddl = document.getElementById('DropDownList1');
for (i = 0; i < ddl.options.length; i++) {
ddlArray[i] = ddl.options[i].value;
}
var str = document.getElementById("TextBox1").value;
str = str.replace(/^\s+|\s+$/g, ""); // strip leading and trailing spaces
str = str.toLowerCase().replace(/\b[a-z]/g, function (w) {
return w.toUpperCase()
}); // reformat to lower-case with initial capital
var match = false;
for (var i = 0; i < ddlArray.length; i++) {
if (str == ddlArray[i]) {
match = true;
}
}
if (match) {
alert("The name " + str + " does match our list!");
document.getElementById("TextBox1").value = "";
return false;
} else {
return true;
}
}
</script>
Try this:
function chkName() {
"use strict";
var ddlArray = [],
ddl = document.getElementById('DropDownList1'),
str = document.getElementById("TextBox1").value,
match = false;
for (var i = 0; i < ddl.options.length; i++) {
ddlArray[i] = ddl.options[i].value;
}
str = str.replace(/^\s+|\s+$/g, "");
str = str.toLowerCase().replace(/\b[a-z]/g, function( w ) {
return w.toUpperCase();
});
for (i = 0; i < ddlArray.length; i++) {
if ( str === ddlArray[i] ) {
alert("The name " + str + " does match our list!");
document.getElementById("TextBox1").value = "";
return false;
}
}
return true;
}

Categories

Resources