<div id="main">
<div class="navigate">
<ul>
<li>
<span>xm</span> »
</li>
<li>
<span>Admin</span> »
</li>
<li>
<span>change</span>
.......
From this html code I have to get random generated data "random02342=randomvaluetoo320230" in variable, which is random generated both random0234 and random value too. How I can achieve this via Javascript (jquery or not)?
EDIT: random02342 and randomvaluetoo320230 is randomly server-side generated.. so its like every time new hash like 1stHash4324kjkjdas324324=And2ndAnotherHash324324asd23432
This would get it, though it's probably not going to win any awards for elegance:
var m = document.getElementById('main').innerHTML.match(/random(\d+)=randomvaluetoo(\d+)/);
// m[1] and m[2] are the two random values.
based on your comment:
var value = $('selector').attr('href').split(';')[2].split('=');
this will give you value[0] - name, and value[1] - value
However this is only if there 3 query params and the random one is the third
Also this might be usefull Parse query string in JavaScript
var first, second;
var q = $('.navigate ul li a[href*="change=name"]').attr('href').split(';').filter(
function() {
return this.contains('random');
}
).join().replace(/[a-zA-z]/g, '').split('=');
first = q[0];
second = q[1];
Related
I am fairly new to Javascript and am trying to learn to write a program that shows a text in one language (eg. Spanish) and has an input box, where the user will type the translated (eg. English) word. The user input would then be compared to the translated word to see if they are the same. I also want to allow some tolerance in case the user inputs a word without an accent if there is supposed to be one (eg. esta instead of está) it won't be counted wrong. If they are not the same I want to be able to show the correct word compared to what the user put. I've been trying to work on this for quite some time but have been getting stuck frequently (for instance, when I run the other function to check the values it opens a new instance when I want it all to be displayed on the same page). Any help with this would be greatly appreciated. Here's what I have so far:
<!DOCTYPE html>
<html>
<head>
<title>Flashcards</title>
</head>
<body>
<script>
var number = Math.floor((Math.random()*2));
var spanish_word = ["hola","adios"]
var Spanish = spanish_word[number];
var english_word = ["hi","bye"];
var English = english_word[number];
document.write("Spanish: " + Spanish);
</script>
<p>English Translation: <input id="english_word" type="text" name="LastName" value="" ></p>
<input type="button" id="myBtn" onclick="check()" value="Check">
<input type="button" id="button" onclick="differentword()" value="Different Word">
<script>
function check()
{
var english_word= document.getElementById('english_word').value;
if (english_word == English) {
document.write("Correct");
}
else {
document.write("Wrong: ");
document.write(Spanish+" in English is "+English);
}
}
function differentword() {
var number = Math.floor((Math.random()*2));
var spanish_word = ["hola","adios"]
var Spanish = spanish_word[number];
var english_word = ["hi","bye"];
var English = english_word[number];
document.write("Spanish: " + Spanish);
}
</script>
</body>
</html>
Or, if you want to see how it runs, you can check it out here https://code.sololearn.com/WXHZ5aAcE3dg/#html.
You got 2 problems here.
You haven't set the current <input id="english_word" type="text" name="LastName" value=""> any value at all (by both html/js). You should set it to the current word (as a string) to manipulate it later.
the if statement if (english_word == English) is broken because it checks if english word, which is a string, equals to an array. and its not, and will never be.
However, checking if the current string word equals to a string, is not a good way in my option. I would like better to use an index to current word that is showing and manipulating that index.
What I suggest is you fix the above by using a new variable: current_word_index, so you can use it in program to check the answer by knowing the current word that is showing.
This next code is just an example of how to currently retrieve by index from arrays:
var current_word_index = 0; // this 0 will change to rand()
var english_word = ["hi","bye"];
english_word[current_word_index];
// english_word will be string "hi".
Here's my full answer:
https://fiddle.jshell.net/j44fjh35/15/
Summary of your question
My understanding is your trying to test the users knowledge on a secondary language ie: Spanish, French etc.
Solution
Switch or If statements are ways to test and compare variables against one another
what you will need to do is first of all convert the string variable to lowercase to ensure that what ever the user types in is always the same.
You will also need to fix some of your code.
So lets look at that first...
var number = parseInt((Math.random()*1));
var spanish_word = ["hola","adios"];
spanish_word is an array which starts from 0 not 1.
Your randomly generated number stored as "number", will equally need to be 0 or 1, simple integer will be sufficient.
Unless your submitting this to a server to be handled by some backend code in PHP or ASP etc, you dont need the "name" attribute here
name="LastName"
You are then over-riding the array
At the start you are setting the array with the following values
var english_word = ["hi","bye"];
But when you click the button to check if you have the right answer
You are erasing the above and telling it to be what ever the user typed in
var english_word= document.getElementById('english_word').value;
There is no need to keep setting and un-setting the array
Try to use better naming convensions for your variables
abbreviate them with what data types they are:
arrEnglishWord to symbolise its an array
strEnglishWord to symbolise it is a string
intEnglishISOCode to symbolise a numerical integer
blEnlish to symbolise a boolean
A lot of code repetition:
Using the an event listener you can save the code repetition
document.addEventListener("DOMContentLoaded", differentword, false);
will make the function differentword run when the page loads, allowing you to get rid of the repeated code at the top
Solution
We need to make the comparison fair (ie not case sentisive)
var strAnswerGiven = english_word.toLowerCase();
var strCorrectAnswer = English.toLowerCase();
if (strAnswerGiven == strCorrectAnswer) {
var arrSpanishWords = ["Hola", "Adios", "Purta", "Luz"];
var arrEnglishWords = ["Hello", "Goodbye", "Door", "Light"];
var strWord = undefined;
var divAnswer = undefined;
function funCheck(elName){
var stAnswer = document.querySelector("#" + elName).value;
var stAnswerGiven = stAnswer.toLowerCase();
var stAnswerExpected = strWord.toLowerCase();
if (stAnswerGiven == stAnswerExpected){
divAnswer.style.color = "#0F0";
divAnswer.innerHTML = "Correct";
}else{
divAnswer.style.color = "#F00";
divAnswer.innerHTML = "Wrong";
}
}
function funNewQuestion(){
var intRandomQNum = parseInt(Math.random() * arrSpanishWords.length);
var elDisplayQuestion = document.getElementById("divWord");
divAnswer = document.getElementById("divAnswerIs");
divAnswer.innerHTML = "";
elDisplayQuestion.innerHTML = arrSpanishWords[intRandomQNum];
strWord = arrEnglishWords[intRandomQNum];
}
document.addEventListener("DOMContentLoaded", funNewQuestion(), false);
Word: <div id="divWord"></div><div id="divAnswerIs"></div>
Answer: <input type="text" id="frmTxtAnswer">
<button id="check" onclick="funCheck('frmTxtAnswer')">Check Answer</button>
<button id="check" onclick="funNewQuestion()">Next Question</button>
I need to retrieve some portion of data from HTML code. Here it is :
<span
class="Z3988" style="display:none;"
title="ctx_ver=Z39.88-2004&rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Ajournal&
rfr_id=info%3Asid%2Focoins.info%3Agenerator&rft.genre=article&
rft.atitle=Parliamentarism Rationalized&
rft.title=East European Constitutional Review&
rft.stitle=E. Eur. Const. Rev.&rft.date=1993&
rft.volume=2&rft.spage=33&rft.au=Tanchev, Evgeni&
rft_id=http://heinonline.org/HOL/Page?handle%3Dhein.journals/eeurcr2%26id%3D33%26div%3D%26collection%3D">
</span>
I tried to use e.g.:
document.querySelector("span.Z3988").textContent
document.getElementsbyClassName("Z3988")[0].textContent
My final aim is to get what comes after:
rft.atitle (Parliamentarism Rationalized)
rft.title (East European Constitutional Review)
rft.date
rft.volume
rft.spage
rft.au
How do I do that? I'd like to avoid RegEx.
Get the title text of span,
Spit it at = , join using character that will not appear in the string I prepared ^, do same for ;, and split at unique character used ^ in this case and then pick value at every even index. If you need string just join it.
Example Sinppet:
var spanTitle = document.getElementsByClassName("Z3988")["0"].getAttribute("title");
var data = spanTitle.split("=").join("^").split(";").join("^").split("^")
var finaldata = data.filter(function(d, index) {
return !!index % 2;
})
console.log(finaldata)
<span class="Z3988" style="display:none;" title="ctx_ver=Z39.88-2004&rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Ajournal&
rfr_id=info%3Asid%2Focoins.info%3Agenerator&rft.genre=article&
rft.atitle=Parliamentarism Rationalized&
rft.title=East European Constitutional Review&
rft.stitle=E. Eur. Const. Rev.&rft.date=1993&
rft.volume=2&rft.spage=33&rft.au=Tanchev, Evgeni&
rft_id=http://heinonline.org/HOL/Page?handle%3Dhein.journals/eeurcr2%26id%3D33%26div%3D%26collection%3D">
</span>
What you have in your title looks to be a url search query...
var elm = document.querySelector('.Z3988')
var params = new URLSearchParams(elm.title) // parse everything
console.log(...params) // list all
console.log(params.get('rft.title')) // getting one example
<span class="Z3988" style="display:none;" title="ctx_ver=Z39.88-2004&rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Ajournal&rfr_id=info%3Asid%2Focoins.info%3Agenerator&rft.genre=article&rft.atitle=Parliamentarism Rationalized&rft.title=East European Constitutional Review&rft.stitle=E. Eur. Const. Rev.&rft.date=1993&rft.volume=2&rft.spage=33&rft.au=Tanchev, Evgeni&rft_id=http://heinonline.org/HOL/Page?handle%3Dhein.journals/eeurcr2%26id%3D33%26div%3D%26collection%3D"></span>
If you're trying to grab the title attribute:
document.getElementsByClassName("Z3988")[0].getAttribute("title");
The way you're outputting content as text is a really bad method. You could try to print each section of your text into element attributes and retrieve each part with element.getAttribute().
Ex:
<span id='whatever' stitle='content' spage='content'></span>
and retrieve from the selected element.
For the way you have it you might want to try to put that text into a variable and split the values like:
var element_text = document.getElementsbyClassName("Z3988")[0].textContent;
var element_specifics = element_text.split(';'); // Separate the text into array splitting by the ';'
Not sure how this is going to process down with browser compatibilities or JavaScript versions, but you can definitely sub out the arrow functions for vanilla anonymous functions, and "let" for "var". Otherwise, it fits the parameters of no regex, and even creates a nice way to index for your various keywords.
My steps:
Grab the attribute block
Split it up into array elements containing the desired keywords and contents
Split up the desired keywords and contents into sub-arrays
Trim down the contents of each keyword block for symbols and non alphanumerics
Construct the objects for convenient indexing
Obviously the last portion is just to print out the array of objects in a nice readable format. Hope this helps you out!
window.onload = function() {
let x = document.getElementsByClassName('Z3988')[0].getAttribute('title')
let a = x.split('rft.').map((y) => y.split('='))
a = a.map((x, i) => {
x = x.map((y) => {
let idx = y.indexOf('&')
return y = (idx > -1) ? y.slice(0, idx) : y
})
let x1 = x[0], x2 = x[1], obj = {}
obj[x1] = x2
return a[i] = obj
})
a.forEach((x) => {
let div = document.createElement('div')
let br = document.createElement('br')
let text = document.createTextNode(JSON.stringify(x))
div.appendChild(text)
div.appendChild(br)
document.body.appendChild(div)
})
}
<span
class="Z3988" style="display:none;"
title="ctx_ver=Z39.88-2004&rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Ajournal&
rfr_id=info%3Asid%2Focoins.info%3Agenerator&rft.genre=article&
rft.atitle=Parliamentarism Rationalized&
rft.title=East European Constitutional Review&
rft.stitle=E. Eur. Const. Rev.&rft.date=1993&
rft.volume=2&rft.spage=33&rft.au=Tanchev, Evgeni&
rft_id=http://heinonline.org/HOL/Page?handle%3Dhein.journals/eeurcr2%26id%3D33%26div%3D%26collection%3D">
</span>
I am currently working on a project that will allow me to bring in a string that would have a designated token that I will grab, get the designated value and remove the token and push to an array. I have the following condition which I am using split in JavaScript but it is not splitting on the designated ending token.
This is the beginning string
"~~/Document Heading 1~~<div>This is a test <b>JUDO</b> TKD</div>~~end~~<div class="/Document Heading 1">This is a test <b>JUDO</b> TKD</div>"
Current Code Block
var segmentedStyles = [];
var contentToInsert = selectedContent.toString();
var indexValue = selectedContent.toString().search("~~");
if (indexValue <= 0) {
var insertionStyle = contentToInsert.split("~~");
segmentedStyles.push(insertionStyle);
}
The designated token is enclosed by a "~~ .... ~~". In this code Block it is going through the condition but the string it is not splitting correctly. I am currently getting the Following string pushed to my array.
This is my current result
[,/Document Heading 1<div>This is a test <b>JUDO</b> TKD</div>end,
<div class="/Document Heading 1">This is a test <b>JUDO</b> TKD</div>]
My Goal
I would like to split a string that is coming in if a token is present. For example I would like to split a string starting from ~~.....~~ through ~~end~~. The array should hold two values like the following
segmentedStyles = [<div>This is a test <b>JUDO</b> TKD</div>],[<div class="/Document Heading 1">This is a test <b>JUDO</b> TKD</div>]
You could use a regular expression for matching the parts.
var string = '~~/Document Heading 1~~<div>This is a test <b>JUDO</b> TKD</div>~~end~~<div class="/Document Heading 1">This is a test <b>JUDO</b> TKD</div>',
array = string.split('~~').filter(function (_, i) {
return i && !(i % 2); // just get element 2 and 4 or all other even indices
});
console.log(array);
Assuming the string always starts with ~~/ you could use the following regex to get the array you want
~~([^\/].*)~~end~~(.*)
https://regex101.com/r/hJ0vM4/1
I honestly didn't quite understand what you're trying to accomplish haha, but I sort of understood what you're trying to do :)
First, just trying to make it clear some stuff. If you split() your string using /~~/ as the Regular Expression for splitting you'll get all the bits surrounded by "~~" in an array, like you did.
Second, if you change the tokens to ~~START~~ and ~~END~~ (tokens that never change) you can accomplish what you want by simply doing string.split(/~~(START|END)~~/) - Much shorter and quicker ;)
Third is the string always in the format ~~<something>~~THE STUFF YOU WANT~~end~~MORE STUFF YOU WANT? If it is, I'd suggest doing this:
function splitTheTokens(str) {
var result = [];
var parts = str.split(/~~end~~/);
for (var i = 0; i < parts.length; i++) {
if (!parts[i]) { continue; } // Skips blanks
if (parts[i].indexOf("~~") == 0) {
// In case you want to do something with the name thing:
var thisPartName = parts[i].substring(2, parts[i].indexOf("~~", 2));
// What (I think) you actually want
var thisPartValue = parts[i].substring(thisPartName.length + 4);
result.push(thisPartValue);
}
else {
result.push(parts[i]);
}
}
return result;
}
Hope this helps :D
I got a question while I parse html using JQuery.
Let me have a simple example for my question.
As you might definitely know, when I need to parse ...
<li class="info"> hello </li>
I get text by
$(".info").text()
my question is.. for given full html and token of text ,can I find query string ?
in case of above example, what I want to get is.
var queryStr = findQuery(html,"hello") // queryStr = '.info'
I know there might be more than one result and there would be various type of expression according to DOM hierarchy.
So.. generally... If some text (in this example, 'hello' ) is unique in the whole HTML, I might guess there must be a unique and shortest 'query' string which satisfies $(query).text() = "hello"
My question is.. If my guess is valid, How can I get unique (and if possible, shortest ) query string for each given unique text.
any hint will be appreciated, and thx for your help guys!
I create a little function that may help you:
function findQuery(str) {
$("body").children().each(function() {
if ( $.trim($(this).text()) == $.trim(str) ) {
alert("." + $(this).attr("class"))
}
});
}
See working demo
I am not sure what you're actually trying to achieve, but, based on your specific question, you could do the following.
var queryStr = findQuery($('<li class="info"> hello </li>'), "hello"); // queryStr = '.info'
// OR
var queryStr = findQuery('<li class="info"> hello </li>', "hello"); // queryStr = '.info'
alert (queryStr); // returns a string of class names without the DOT. You may add DOT(s) if need be.
function findQuery(html, str) {
var $html = html instanceof jQuery && html || $(html);
var content = $html.text();
if ( content.match( new RegExp(str, "gi") ) ) {
return $html.attr("class");
}
return "no matching string found!";
}
Hope this demo helps you!!
$(document).ready(function() {
var test = $("li:contains('hello')").attr('class');
alert(test);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li class="info">hello</li>
</ul>
Have used the jQuery attribute ":contains".
im making a small smiley script , what it does is to change ::1:: into an image html for a div.
the code as follow:
var smileys = {
'1': 'http://domain.com/smiley1.gif',
'2': 'http://domain.com/smiley2.gif',
'3': 'http://domain.com/smiley3.gif'
};
function checksmileys(){
x$('.message').each(function()
var start = '<img src="';
var end = '">';
x$(this).html( x$(this).html().replace(/::(\d+)::/g, start + smileys['$1'] + end) );
});
Checksmileys function is triggered by user event.
However it is not able to get the digit(which is the id) out of a sentence.
It kept on producing this <img src="undefined">
My HTML example as follows:
<div id="chat">
<ul>
<li class="message">Hi john</li>
<li class="message">what are you doing</li>
<li class="message">::1:: nothing</li>
<li class="message">hi</li>
<li class="message">nice to meet you ::1::</li>
</ul>
</div>
Where is my problem here?
I guess you need a function here:
html = html.replace(/::(\d+)::/g, function($0, $1) { return start + smileys[$1] + end })
here's when the functional form of html() comes in handy
$(this).html(function(_, oldhtml) {
return oldhtml.replace(/::(\d+)::/g, function($0, $1) {
return start + smileys[$1] + end;
})
})
In JavaScript, property names don't have prefixes like they often do in PHP. The name of the property you create in your smileys object is 1, not $1, so change smileys['$1'] to smileys['1'].
Update: From your comment below, it seems you're trying to use $1 to refer to the capture group. That only works when $1 is part of the string you pass in, but the expression start + smileys['$1'] + end is evaluated before the call to replace and then passed into it. smileys['$1'] will be undefined.
Since you're trying to do a lookup, your best bet is to pass in a function that does the lookup:
x$(this).html( x$(this).html().replace(/::(\d+)::/g, function(m, c1) {
return start + smileys[c1] + end;
}) );
c1 is the text of the first capture group. More
You've called it an array, which I'm guessing is because you're used to the term "associative array" from PHP. Your smileys object is just an object, not an array. In JavaScript, when we say "array", we mean something created via [] or new Array, which has specific handling for a certain class of property names (numeric ones), a special length property, and some handy array-like functions. What you've done with smileys is perfectly fine and completely normal, we just tend not to use the word "array" for it ("map" is more common in the JS world).