I am trying to have sql's like clause like effect in javascript.
I am aware that similar question are already present on internet but the following approach is not working for me:
$(document).ready(function() {
var listAll = [
"X1",
"ANTENNA SYSTEMS 00000000AS",
"Security & Wrokf 00000000CS",
"MICROWAVE & COMM 00000000MC",
"MICROWAVE SENSOR 00000000MT",
"PLANNING & PROJE 00000000PG",
"MECHANICAL SYSTE 00000000MS",
"ELECTRO-OPTICAL 00000000EO",
"SATCOM EXPERIMEN 00000000SE",
"QUALITY ASSURANC 00000000QA",
"QUALITY ASSURANC 00000000QC",
"DATA PRODUCTS SO 00000000DP"
];
var lstfiltered = ["X2"];
for (i = 0; i <= listAll.length - 1; i++) {
console.log(listAll[i]);
var string = listAll[i];
var substring = "lan";
if (string.indexOf(substring) !== -1) {
lstfiltered.push(string);
}
}
console.log(lstfiltered);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
I have set substring which is to be looked up in string as "lan", which should push "PLANNING & PROJE 00000000PG" into the array. But it does not.
I think that the problem is with the letter casing. Try this :
$(document).ready(function() {
var listAll = ["X1", "ANTENNA SYSTEMS 00000000AS", "Security & Wrokf 00000000CS", "MICROWAVE & COMM 00000000MC", "MICROWAVE SENSOR 00000000MT", "PLANNING & PROJE 00000000PG", "MECHANICAL SYSTE 00000000MS", "ELECTRO-OPTICAL 00000000EO", "SATCOM EXPERIMEN 00000000SE", "QUALITY ASSURANC 00000000QA", "QUALITY ASSURANC 00000000QC", "DATA PRODUCTS SO 00000000DP"];
var lstfiltered = ["X2"];
for (i = 0; i <= listAll.length - 1; i++) {
console.log(listAll[i]);
var string = listAll[i];
var substring = "lan";
if (string.toLowerCase().indexOf(substring) !== -1) {
lstfiltered.push(string);
}
}
console.log(lstfiltered);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
I suggest to search for lower case letters and move the search string outside of the loop.
$(document).ready(function() {
var listAll = ["X1", "ANTENNA SYSTEMS 00000000AS", "Security & Wrokf 00000000CS", "MICROWAVE & COMM 00000000MC", "MICROWAVE SENSOR 00000000MT", "PLANNING & PROJE 00000000PG", "MECHANICAL SYSTE 00000000MS", "ELECTRO-OPTICAL 00000000EO", "SATCOM EXPERIMEN 00000000SE", "QUALITY ASSURANC 00000000QA", "QUALITY ASSURANC 00000000QC", "DATA PRODUCTS SO 00000000DP"];
var lstfiltered = ["X2"];
var substring = "lan";
for (i = 0; i <= listAll.length - 1; i++) {
console.log(listAll[i]);
var string = listAll[i];
if (string.toLowerCase().indexOf(substring) !== -1) {
lstfiltered.push(string);
}
}
console.log(lstfiltered);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
For a more concise version, you could use Array#filter
$(document).ready(function() {
var listAll = ["X1", "ANTENNA SYSTEMS 00000000AS", "Security & Wrokf 00000000CS", "MICROWAVE & COMM 00000000MC", "MICROWAVE SENSOR 00000000MT", "PLANNING & PROJE 00000000PG", "MECHANICAL SYSTE 00000000MS", "ELECTRO-OPTICAL 00000000EO", "SATCOM EXPERIMEN 00000000SE", "QUALITY ASSURANC 00000000QA", "QUALITY ASSURANC 00000000QC", "DATA PRODUCTS SO 00000000DP"];
var substring = "lan";
var lstfiltered = listAll.filter(function (a) {
return a.toLowerCase().indexOf(substring) !== -1;
});
lstfiltered.unshift('X2')
console.log(lstfiltered);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
If you want to push original string then compare with string converted by using toLowerCase() and push the original string as shown below :
$(document).ready(function() {
var listAll = ["X1", "ANTENNA SYSTEMS 00000000AS", "Security & Wrokf 00000000CS", "MICROWAVE & COMM 00000000MC", "MICROWAVE SENSOR 00000000MT", "PLANNING & PROJE 00000000PG", "MECHANICAL SYSTE 00000000MS", "ELECTRO-OPTICAL 00000000EO", "SATCOM EXPERIMEN 00000000SE", "QUALITY ASSURANC 00000000QA", "QUALITY ASSURANC 00000000QC", "DATA PRODUCTS SO 00000000DP"];
var lstfiltered = ["X2"];
for (i = 0; i <= listAll.length - 1; i++) {
console.log(listAll[i]);
var string = listAll[i].toLowerCase();
var substring = "lan";
if (string.indexOf(substring) !== -1) // compare with string converted by toLowerCase()
{
lstfiltered.push(listAll[i]); // Push original string.
}
}
console.log(lstfiltered);
});
Related
Here I am making a word conversion tool which changes a certain word X into Y, or X to Y to Z by using javascript.
Progress: HERE
Here is the entire javascript:
var conversion = {
"one":"two",
};
var conversion2 = {
"two":"three",
};
var maxLength = Object.keys(conversion)
.reduce((a, b) => a.length > b.length ? a : b)
.length;
function convert (text) {
var converted = "";
var cur = 0;
while (cur < text.length) {
var testedPhoneme;
var symbol = undefined;
for (var length = maxLength; length > 0; length --) {
testedPhoneme = text.substr(cur, length);
if (conversion[testedPhoneme]) {
symbol = conversion[testedPhoneme];
break; // stop the loop
}
}
if (symbol) {
converted += symbol;
cur += testedPhoneme.length;
}
else {
converted += text[cur]
cur++;
}
}
return converted
}
var maxLength2 = Object.keys(conversion2)
.reduce((a, b) => a.length > b.length ? a : b)
.length;
function convert2 (text) {
var converted2 = "";
var cur2 = 0;
while (cur2 < text.length) {
var testedPhoneme2;
var symbol2 = undefined;
for (var length = maxLength2; length > 0; length --) {
testedPhoneme2 = text.substr(cur2, length);
if (conversion2[testedPhoneme2]) {
symbol2 = conversion2[testedPhoneme2];
break; // stop the loop
}
}
if (symbol2) {
converted2 += symbol2;
cur2 += testedPhoneme2.length;
}
else {
converted2 += text[cur2]
cur2++;
}
}
return converted2
}
function onInputTextChange(txt) {
var outputTextareaElem = document.getElementById("output_textarea");
var div = document.createElement("div");
var outputHtmlEntities = convert(txt);
div.innerHTML = outputHtmlEntities;
outputTextareaElem.value = div.innerText;
}
function onOutputTextChange(txt) {
var outputTextareaElem2 = document.getElementById("output_textarea2");
var div = document.createElement("div");
var outputHtmlEntities2 = convert2(txt);
div.innerHTML = outputHtmlEntities2;
outputTextareaElem2.value = div.innerText;
}
In the page that I made so far, there are three <textarea>s; Input, Output and Output2.
Currently, thanks to this piece of code;
var conversion = {
"one":"two",
};
var conversion2 = {
"two":"three",
};
If one is typed into Input, Output renders two. If two is manually typed into Output, three gets rendered in Output2.
Here is the problem, I want to render three in Output2 only through typing one into Input, but a direct two-step conversion seems unavailable yet. In other words, Input > Output (one > two) and Output > Output2 (two > three) conversion is available, but Input > Output > Output2 (one > two > three) is unavailable.
What needs to be done to solve this? Any help would be appreciated.
Ok, not exactly what you asked, but I could do something that works
Here is the example : https://jsfiddle.net/alias_gui3/8knw57u0/94/
how to use it :
to add new characters OR new languages/scripts
just complete the dictionnary :
var dictionnary = [
{
latin: "u",
japanese: "う",
emoji: "👋"
// add any script for every characters
},{
latin: "ku",
japanese: "く",
emoji: "👀"
},{
latin: "tsu",
japanese: "つ",
emoji: "🤖"
}
// add any character with the same format
]
to add new textareas :
give your textarea a recognizable id (eg. id="cyrillic")
then connect your textarea with this method:
// connect your textareas below !!
addTextArea(
document.querySelector("#latin"),
"latin"
);
addTextArea(
document.querySelector("#japanese"),
"japanese"
);
addTextArea(
document.querySelector("#emoji"),
"emoji"
);
// add new textarea with a new language here
then all the connections are done, you can edit all your textareas, if they recognise a character they will translate it in all the other textareas
full code
var dictionnary = [
{
latin: "u",
japanese: "う",
emoji: "👋"
// add any script for every characters
},{
latin: "ku",
japanese: "く",
emoji: "👀"
},{
latin: "tsu",
japanese: "つ",
emoji: "🤖"
}
// add any character with the same format
]
// calculate the max length for each language :
var max = {}
dictionnary.forEach(
char => {
Object.keys(char).forEach(script => {
max[script] = max[script]
? char[script].length > max[script]
? char[script].length
: max[script]
: char[script].length
})
}
)// now max contains the maximum length of sequence
// for each language
function findSymbol (
originSymbol,
originScript,
destinationScript
) {
for (var i = 0; i < dictionnary.length; i++) {
var char = dictionnary[i];
if (char[originScript] === originSymbol) {
return char[destinationScript]
}
}
return false // if not found
}
function translate (
text,
originScript,
destinationScript
) {
var cur = 0;
var translated = "";
var maxLength = max[originScript]
while (cur < text.length) {
var testedPhoneme;
var symbol = false;
for (var length=maxLength; length > 0; length--) {
testedPhoneme = text.substr(cur, length);
symbol = findSymbol(
testedPhoneme,
originScript,
destinationScript
)
if (symbol) {
break; // stop the loop
}
}
if (symbol) {
translated += symbol;
cur += testedPhoneme.length;
}
else {
translated += text[cur];
cur++;
}
}
return translated
}
var textareas = []; // the list of your textareas
function addTextArea(element, originScript) {
textareas.push({
element: element,
script: originScript
})
element.addEventListener("input", function (e) {
signalTextChanged(element, originScript)
});
}
function signalTextChanged (
originElement,
originScript
) {
var originText = originElement.value;
textareas.forEach(function (textarea) {
if (textarea.element !== originElement) {
var translated = translate(
originText,
originScript,
textarea.script
)
textarea.element.value = translated;
}
})
}
// connect your textareas below !!
addTextArea(
document.querySelector("#latin"),
"latin"
);
addTextArea(
document.querySelector("#japanese"),
"japanese"
);
addTextArea(
document.querySelector("#emoji"),
"emoji"
);
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript">
</script>
</head>
<body>
<center>
<h1>Latin to foreign script converter 3</h1>
<p>type in u, ku, tsu in the FIRST panel</p>
<textarea
id="latin"
autofocus=""
placeholder="type text in latin ! (u ku or tsu)"
rows="10"
style="width:300px"></textarea>
<textarea
id="japanese"
rows="10"
placeholder="type text in japanese !"
style="width:300px"></textarea>
<textarea
id="emoji"
rows="10"
placeholder="type text in emojis !!"
style="width:300px"></textarea>
</center>
</center>
</body>
</html>
I'm not sure if I fully understand what you're trying to achieve here
There are some duplications in your code, what if you'll have 10 fields for output, will you create a special function for each of them?
Try to simplify things.
One way would be to loop through all of your lists as follows:
Put all your conversation in a list
var lists = [conversion, conversion2];
Add isInNextList function to check if your text is a key in the next list
function isInNextList(index, key) {
if (lists.length < index) {
return false;
}
return Object.keys(lists[index]).includes(key);
}
change your onInputTextChange function as follow:
function onInputTextChange(txt) {
var index = 0;
var text = txt;
while (isInNextList(index, text)) {
var outputTextareaElem = document.getElementById(
'output_textarea_' + index
);
var div = document.createElement('div');
text = lists[index][text]; //next key
index++;
div.innerHTML = text;
outputTextareaElem.value = div.innerText;
}
}
change your output textarea's ids to contain the index
id="output_textarea_0"
id="output_textarea_1"
There are other improvements that can be made like:
Creating the output fields dynamically,
Clear output fields etc.
I am trying to match word from a content and if word is matched then i want to show other content.
var match = 'song.mp3';
if( // in match find .mp3 ) {
$('.show').text('true');
} else {
$('.show').text('error');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="show"></div>
An example of checking text inside string is
str = "abc.mp3";
var n = str.search(".mp3");
if(n > -1)
document.write('found');
else
document.write('not found');
you can simply try this
if(match.match(/\.mp3/))
or
var match = 'song.mp3';
var newString = match.split('.');
if(newString === 'mp3'){
....
}
var match = 'song.mp3';
if (match.indexOf('mp3') > -1)
{
$('.show').text('true');
}
else
{
$('.show').text('error');
}
var match = 'song.mp3';
var abc = 'mp3'
if(abc.test(match))
{
$('.show').text('true');
}
else {
$('.show').text('error');
}
I have this piece of javascript that won't work. It is supposed to take the user input and store it into the player input variable. Then, it splits the string that is returned and splits it into an array which is then converted into an object by the function oc(). Finally, the function analyzeUserInput finds keywords in the input object and places text into the paragraph element called text accordingly. In this example if the user types in slash, poke, slice, hack, etc and the word "sword" the paragraph element is supposed to say "you did 4 damage!" but it doesn't. here's the code:
<!DOCTYPE html>
<html>
<body>
<p>"oh no theres a monster whatchya gonna do?"</p>
<input id="plyrInput" type="text" />
<button onclick="analyzeUserInput()">Try it</button>
<p id="text"></p>
<script>
var plyrInput;
var plyrInputArray;
var plyrInputAnalysis;
function oc() {
plyrInputArray = plyrInput.split(' ');
var plyrInputObj = {};
for (var i = 0; i < plyrInputArray.length; ++i) {
plyrInputObj[plyrInputArray[i]] = ' ';
}
return plyrInputObj;
}
function analyzeUserInput() {
plyrInput = document.getElementById("plyrInput").text;
oc();
if (plyrInputAnalysis in oc(['use', 'slash', 'hack', 'wield', 'slice', 'sever', 'dismember', 'poke', 'cripple', 'maim', 'mutilate', 'chop', 'rend']) && plyrInputAnalysis in oc(['sword'])) {
document.getElementById("text").innerHTML = "You did 4 damage with your sword!";
}
}
</script>
</body>
</html>
var plyrInput;
var plyrInputArray;
var plyrInputAnalysis;
function oc() {
plyrInputArray = plyrInput.split(' ');
var plyrInputObj = {};
for (var i = 0; i < plyrInputArray.length; ++i) {
//storing these values in an object being blank is not really needed at all!
//plyrInputObj[plyrInputArray[i]] = ' ';
plyrInputObj[i] = plyrInputArray[i]; //acceptable or use the array itself!
}
return plyrInputObj;
}
function analyzeUserInput() {
//plyrInput = document.getElementById("plyrInput").text;//no such property as text
plyrInput = document.getElementById("plyrInput").value;
//you ran this function without storing it so we can't use it
//oc();
var plyrAction = oc();
//you call an undefined variable `plyrInputAnalysis`. So what are we going to do with it?
if (plyrInputAnalysis in oc(['use', 'slash', 'hack', 'wield', 'slice', 'sever', 'dismember', 'poke', 'cripple', 'maim', 'mutilate', 'chop', 'rend']) && plyrInputAnalysis in oc(['sword'])) {
document.getElementById("text").innerHTML = "You did 4 damage with your sword!";
}
}
Now for the fix:
var plyrInput;
var plyrInputArray;
var plyrInputAnalysis;
//added an acitonList for later usage for yourself
var actionList = {
'use':4,
'slash':4,
'hack':4,
'wield':4,
'slice':4,
'sever':4,
'dismember':4,
'poke':4,
'cripple':4,
'maim':4,
'mutilate':4,
'chop':4,
'rend':4
};
function oc() {
plyrInputArray = plyrInput.split(' ');
var plyrInputObj = {};
for (var i = 0; i < plyrInputArray.length; ++i) {
plyrInputObj[i] = plyrInputArray[i];
}
return plyrInputObj;
}
function analyzeUserInput() {
plyrInput = document.getElementById("plyrInput").value;
var plyrAction = oc(); //cached the returned value from oc
for(var item in plyrAction){ //looping through the plyrActions object
if(actionList[plyrAction[item]]){ //if there is a plyrAction that matches the actionsList we'll continue.
document.getElementById("text").innerHTML = "You did "+actionList[plyrAction[item]]+" damage with your sword!";
}
}
}
Though this could seems more complicated than it needs to be I went off your original methodology, you could create a better instance of this code for an RPG game, though it would be good to look into an IIFE to wrap this in and minimize a lot of the code instead of multiple functions.
For instance
function analyzeUserInput() {
plyrInput = document.getElementById("plyrInput").value;
var plyrAction = plyrInput.split(' ');
var plyrInputObj = {};
for (var i = 0; i < plyrAction.length; ++i) {
plyrInputObj[i] = plyrAction[i];
}
for(var item in plyrInputObj ){
if(actionList[plyrInputObj[item]]){
document.getElementById("text").innerHTML = "You did "+actionList[plyrInputObj[item]]+" damage with your sword!";
}
}
}
This question already has answers here:
XML parsing of a variable string in JavaScript
(10 answers)
Closed 9 years ago.
I have an xml string that I need to pull a value from using only JavaScript. Here's an example of the xml string:
<RequestVars>
<BuyerCookie>O7CPHFP7AOY</BuyerCookie>
<Extrinsic name="CostCenter">670</Extrinsic>
<Extrinsic name="UniqueName">catalog_tester</Extrinsic>
<Extrinsic name="UserEmail">catalog_tester#mailinator.com</Extrinsic>
</RequestVars>
And I need to get the email address from it (i.e. catalog_tester#mailinator.com). I have a way to pull the value for a given unique element, such as getting O7CPHFP7AOY for BuyerCookie using this function:
function elementValue(xml, elem) {
var begidx;
var endidx;
var retStr;
begidx = xml.indexOf(elem);
if (begidx > 0) {
endidx = xml.indexOf('</', begidx);
if (endidx > 0)
retStr = xml.slice(begidx + elem.length,
endidx);
return retStr;
}
return null;
}
But now, I need a way to look up the value for the "Extrinsic" element with the value "UserEmail" for attribute "name". I've seen a couple ways to accomplish this in JQuery but none in JavaScript. Unfortunately, for my purposes, I can only use JavaScript. Any ideas?
I came up with a solution. It's a little messy, but it does the tricky. I feed in the string representation of the xml, the name of the element tag I'm looking for, the name of the attribute and the attribute value I am seeking an element value for.
function elementValueByAttribute(xml, elem, attrName, attrValue) {
var startingAt = 1;
var begidx;
var mid1idx;
var mid2idx;
var endidx;
var aName;
var retStr;
var keepGoingFlag = 1;
var count = 0;
while (keepGoingFlag > 0) {
count++;
begidx = xml.indexOf(elem, startingAt);
if (begidx > 0) {
mid1idx = xml.indexOf(attrName, begidx);
if (mid1idx > 0) {
mid2idx = xml.indexOf(">", mid1idx);
if (mid2idx > 0) {
aName = xml.slice(mid1idx + attrName.length + 2, mid2idx - 1);
if (aName == attrValue) {
endidx = xml.indexOf('</', begidx);
if (endidx > 0)
{
retStr = xml.slice(mid2idx + 1, endidx);
}
return retStr;
}
}
}
}
if (startingAt == mid2idx) {
keepGoingFlag = 0;
} else {
startingAt = mid2idx;
}
}
return null;
}
I am using javascript to cycle through an array of urls within an iframe and so far when the prev or next buttons are pressed it jumps to the first var in the array and both prev and next functions end. Any ideas?
<iframe id="myFrame" src="http://startpage.com" width="484px" height = "424px"></iframe>
<button onclick = "prevPage(); ">Prev</button>
<button onclick = "nextPage(); ">Next</button>
<script>
var sites=new Array();
sites[0]="http://site1.html";
sites[1]="http://site2.html";
sites[2]="http://site3.html";
sites[3]="http://site4.html";
function nextPage() {
var number = document.getElementById("myFrame").src;
number = number.substring(number.length - 4 ,number.length-3);
number = parseInt(number) + 1;
document.getElementById("myFrame").src=sites[0];
}
function prevPage() {
var number = document.getElementById("myFrame").src;
number = number.substring(number.length - 3 ,number.length-4);
number = parseInt(number) - 1;
document.getElementById("myFrame").src=sites[0];
}
</script>
Why are you using the URL as your 'position' storage? It'd be FAR easier to just use a variable:
var curPos = 0;
function nextPage() {
curPos++;
if (curPos >= sites.length) {
curPos = 0;
}
document.getElementById('myframe').src = sites[curPos];
}
function prevPage() {
curPos--;
if (curPos < 0) {
curPos = sites.length - 1;
}
document.getElementById('myframe'.).src = sites[curPos];
}
If I understood your problem correctly I think all you need to do is use document.getElementById("myFrame").src=sites[number]; instead of document.getElementById("myFrame").src=sites[0];
May be
document.getElementById("myFrame").src=sites[number-1];
is what you are trying to do in both functions.