JS. How do I create a regex pattern by concatenation with variables - javascript

I am not able to fix the following:
<html>
<head>
<title>Test</title>
<script>
function myFunction(arr) {
var N = [0,1,2,3,4,5,6,7,8,9];
for (var s in N) {
var pattern = new RegExp('/^[A-z]et_[' + s + ']_\\d/');
// NOTE I get the following, is that how it should be?
// window.alert(pattern); => /\/^[A-z]et_[0]_\d\//
// NOTE: I checked that it works fine for a single digit case, say:
// var pattern = new RegExp(/^[A-z]et_[3]_\d/);
var newarr = arr.filter(elt => pattern.test(elt));
document.getElementById("demo").innerHTML = newarr;
}}
</script>
</head>
<body>
<div id="demo" onclick="myFunction(['aaaLet_0_0', 'Let_1_99', 'Let_2_', 'Let_3_99', 'Pet_2_', 'Pet_3_99', '_9_33']);">click here</div>
<hr>
<p>expected output: Let_1_99, Let_3_99, Pet_3_99</p>
</body>
</html>
I see many similar questions, but I have not been able to find out how to fix my code. It should be possible, shouldn't it?
EDIT
the following is what I need:
<html>
<head>
<title>Test</title>
<script>
var newarr = [];
function myFunction(arr) {
var N = [0,1,2,3,4,5,6,7,8,9];
for (var s in N) {
var pattern = new RegExp('^[A-z]et_' + s + '_\\d'); // NOTE: not /
var lnewarr = arr.filter(elt => pattern.test(elt));
if(typeof lnewarr !== 'undefined' && lnewarr.length > 0){newarr.push(lnewarr)};
}
document.getElementById("demo").innerHTML = newarr;
}
</script>
</head>
<body>
<div id="demo" onclick="myFunction(['aaaLet_0_0', 'Let_1_99', 'Let_2_', 'Let_3_99', 'Pet_2_', 'Pet_3_99', '_9_33']);">click here</div>
<hr>
<p>expected output: Let_1_99, Let_3_99, Pet_3_99</p>
</body>
</html>
(sorry if my post is mostly code. Hope it may helps somebody out there.)

Instead of for loop you can use a .join like this:
var pattern = new RegExp('^[A-Za-z]et_[' + N.join('') + ']_\\d');
//=> /^[A-Za-z]et_[0123456789]_\d/
This works for the case when you have singe character values in your array N.
For generic use you can use this expression:
var pattern = new RegExp('^[A-Za-z]et_(?:' + N.join('|') + ')_\\d');
//=> /^[A-Za-z]et_(?:0|1|2|3|4|5|6|7|8|9)_\d/
Using a for loop you can do this:
var N = [0,1,2,3,4,5,6,7,8,9];
var str='(?:';
for (var s in N)
str += s + '|';
str = str.replace(/\|$/, ')');
var pattern = new RegExp('^[A-Za-z]et_' + str + '_\\d');
//=> /^[A-Za-z]et_(?:0|1|2|3|4|5|6|7|8|9)_\d/

Related

adding math formula string to document using javascript and MathJax

When pressing the button to add the math formula, the MathJax statement does not seem to be interpretet:
const button = document.getElementById('go');
button.addEventListener('click', displayMath, true);
function displayMath() {
const body = document.body;
p = document.createElement('p');
const a = 3, b = 2;
const c = a + b;
const math = "\\(" + a + "+ " + b + " = " + c + "\\)";
p.innerHTML = math;
body.appendChild(p);
}
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" async
src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-MML-AM_CHTML" async>
</script>
</head>
<body>
<p>press the button to display math like this: \(a + b = c\)</p>
<button id="go" type="button">Go!</button>
<script src="test.js"></script>
</body>
</html>
1) Can MathJax statements be addet through events like a button click?
2) If not are there better alternatives?
I appreciate any help, thanks :>
You need to run Mathjax parser again, to convert dynamically added expression to math. Here is documentation.
So, what you need to do is run MathJax.Hub.Queue(); method on your new expression. Your code should looks like this:
const button = document.getElementById('go');
button.addEventListener('click', displayMath, true);
function displayMath() {
const body = document.body;
p = document.createElement('p');
const a = 3, b = 2;
const c = a + b;
const math = "\\(" + a + "+ " + b + " = " + c + "\\)";
p.innerHTML = math;
body.appendChild(p);
MathJax.Hub.Queue(["Typeset", MathJax.Hub, p]);
}
And here is working fiddle

how to store variable`s name in another variable

i`m working on school project
how can i access the name of variable and store it to in another variable ex: y[i].
what to write in place of comment below in javascript code.
var p = ["a","b","d"];
var q = ["d","b","c"];
var value = "d";
var x = [];
var y = [];
function testArrays(needle, arrays) {
for (var i=0; i<arrays.length; i++) {
x[i] = arrays[i].indexOf(value);
// y[i] = // store array`s name here
}
document.getElementById("demo").innerHTML = x + y;
}
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<p>Click the button to display the position of the element "Apple":</p>
<button onclick="testArrays(value, [p, q])">Try it</button>
<p id="demo"></p>
</body>
</html>
Here is what you search for : You have to construct a object with your arrays and pass trow all the arrays.
var obj = {
p:["a","b","d"],
q: ["d","b","c"]
};
var value = "d";
var x = [];
var y = [];
function testArrays(needle, arrays) {
for(key in arrays){
x.push(arrays[key].indexOf(value));
y.push(key);
}
document.getElementById("demo").innerHTML = x + y;
}
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<p>Click the button to display the position of the element "Apple":</p>
<button onclick="testArrays(value, obj)">Try it</button>
<p id="demo"></p>
</body>
</html>
Since you ask for what i was talking about. I'll give you the code.
Again, to re-iterate my point, you cannot get the variable name. But if you must have the variable somehow, you can work around by putting all the variables you need access to in an object.
you will not get the variable name of the object, but you can access all the properties names of this object.
Here is the codepen link to see the code running.
html
<p id="test"><p>
js
var variableList = {};
variableList.var1 = 1;
variableList.var2 = -50;
variableList.var3 = [2,4];
variableList.var4 = "4";
variableList.var5 = 5.5;
var ele = document.getElementById("test");
for(var propertyName in variableList) {
ele.innerHTML = ele.innerHTML + "<br>" + propertyName + " : " + variableList[propertyName];
}

How do i make text = integers

I have a problem that i've been trying to solve for days.
I was wondering if it was possible to let a text turn into an integer.
So everytime i write in my textarea("ALC") Load, then on the textarea("MLC") 001. And also including 1-15 to binary at the end
E.g. Load #1 will show 001 0 00001
<html>
<head>
<center><font size ="24"> Simple Assembler </font></center>
<script type="text/javascript">
var Load = "001";
var Store = "010";
var Add = "011";
var Sub = "100";
var Equal = "101";
var Jump = "110";
var Halt = "111";
var # = "1";
</script>
</head>
<body>
<form name="AssemblyLanguagecode" action="" method="">
<textarea Id="ALC" style="resize:none;width:35%;height:35%;margin-left:15%" value="">Insert Assembly Language Code</textarea>
<textarea Id="MLC" style="resize:none;width:35%;height:35%;" ReadOnly="True">Machine Language Code will be displayed here</textarea><br />
<p align="center"><input type="button" value="Assemble" onclick="ALCtoMLC()";" /></p>
</form>
<script type= "text/javascript">
function ALCtoMLC() {
var x = document.getElementById("ALC").value;
x = parseInt(x);
var bin = x.toString(2);
document.getElementById("MLC").innerHTML = bin;
}
</script>
</body>
</html>
I think I understand what you want to do. You want to use what you type into "ALC" as a key to a value. In that case, you want to use a javascript object and assign the instructions as keys, and the binary to the value. Such as
var instruction_set = {
"Load" : "001",
"Store" : "010",
"Add" : "011",
"Sub" : "100",
"Equal" : "101",
"Jump" : "110",
"Halt" : "111"
}
function ALCtoMLC() {
var x = document.getElementById("ALC").value;
x = instruction_set[x];
}
Updated:
Try this:
<html>
<head>
<center><font size ="24"> Simple Assembler </font></center>
<script type="text/javascript">
var Load = "001";
var Store = "010";
var Add = "011";
var Sub = "100";
var Equal = "101";
var Jump = "110";
var Halt = "111";
var # = "1";
</script>
</head>
<body>
<form name="AssemblyLanguagecode" action="" method="">
<textarea Id="ALC" style="resize:none;width:35%;height:35%;margin-left:15%" value="">Insert Assembly Language Code</textarea>
<textarea Id="MLC" style="resize:none;width:35%;height:35%;" ReadOnly="True">Machine Language Code will be displayed here</textarea><br />
<p align="center"><input type="button" value="Assemble" onclick="ALCtoMLC();" /></p>
</form>
<script type= "text/javascript">
var Dict = { 'Load':"001",'Store':"010"}; //example Instruction set
function ALCtoMLC() {
var x = document.getElementById("ALC").value;
var instrType = '';
for (var instr in Dict){
var ind = x.indexOf(instr);
if( ind > -1){
instrType = instrType + Dict[instr];
x = x.replace(instr,'');
}
}
console.log(instrType, "::", x);
x = parseInt(x);
var bin = x.toString(2);
bin = instrType + bin;
document.getElementById("MLC").innerHTML = bin;
}
</script>
</body>
</html>
Lets say you have a way to get the tokens. Then your function should look like this
var tokens = getTokens( document.getElementById("ALC").value ) ;
var vocabulary = { "Load" : "001" , " ... " } ;
var output = []
var i = 0;
var tokensLength = tokens.length;
for ( ; i < tokensLength; i++){
var token = tokens[i];
if ( isNaN(token) && typeof(vocabulary[token]) != "undefined" ){
output.push( vocabulary[token] );
}else if ( !isNaN(token) ){
output.push( Number(token).toString(2) );
}else{
console.log(["error : unknown token ", token]);
}
}
document.getElementById("MLC").value = output.join(" ");
I see in the question that Load translates to 0010 and not 001, so I would simply modify the vocabulary.
Explanation :
I assume you have a way to split the input to tokens. (the ALC syntax is still unclear to me).
The tokens array will contains, for example ["Load","#","15", "Load","#","16"] and so on.
Then I loop on the tokens.
If a token is a number - I turn it to binary string.
If the token is translatable by vocabulary - I switch it to its binary representation.
Otherwise I print an error.
NOTE: if output should be padded with "0" - even though it is not specified in the question, I would use "0000".substring(n.length) + n
This is how I would do it:
var opcodes = {
Load: 1,
Store: 2,
Add: 3,
Sub: 4,
Equal: 5,
Jump: 6,
Halt: 7
};
var assemblyTextarea = document.querySelector("#assembly");
var machineTextarea = document.querySelector("#machine");
document.querySelector("#assemble").addEventListener("click", function () {
var instruction = assemblyTextarea.value.split(" ");
var operand =+ instruction[1].slice(1);
var opcode = instruction[0];
var code = opcodes[opcode] * 16 + operand;
var bits = ("0000000" + code.toString(2)).slice(-8);
machineTextarea.value = bits;
}, false);
See the demo here: http://jsfiddle.net/fs5mb/1/
The input should be formatted as follows: Load #15

Change first letter in string to uppercase in JavaScript

I have an array of strings,
["item1", "item2"]
I'd like to change my array to
["showItem1", "showItem2"]
The most easy to understand way of doing exactly what you ask for is probably something like this:
var items = ["item1", "item2"];
​for (var i=0;i<items.length;i+=1) {
items[i] = "show" + items[i].charAt(0).toUpperCase() + items[i].substring(1);
}
console.log(items); // prints ["showItem1", "showItem2"]
Explanation: build a new string consisting of the string "show" + the first character converted to uppercase + the remainder of the string (everything after the first character, which has index 0)
Strings are array-like. You could do this:
var arr = ['item1', 'item2'];
for (var i=0, l=arr.length; i<l; i++) {
var letters = arr[i].split('');
arr[i] = 'show' + letters.shift().toUpperCase() + letters.join('');
}
Demo: http://jsbin.com/asivec/1/edit
arr.map(function(i) {
return 'show' + i.charAt(0).toUpperCase() + i.slice(1);
});
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
supported in Chrome, Firefox, IE9 and others.
Here is a reusable firstCharLowerToUpper() function I wrote for that task.
LIVE DEMO
<!DOCTYPE html>
<html>
<head>
<style>
span{
color:red;
}
</style>
</head>
<body>
<div>this is the text:
<span id="spn">
javascript can be very fun
</span>
</div>
<br/>
<input type="button" value="Click Here" onClick="change()"/>
<script>
function firstCharLowerToUpper(x)
{
var ar = x;
for (var i = 0; i < ar.length; i++)
{
ar[i] = ar[i].charAt(0).toUpperCase() + ar[i].substr(1);
}
// join to string just to show the result
return ar.join('\n');
}
function change()
{
var ar = ["javascript ", "can ","be ","very ","fun" ];
var newtxt = firstCharLowerToUpper(ar);
document.getElementById("spn").innerHTML = newtxt;
}
</script>
</body>
</html>

How to create a visual diff view like Stack Overflow does?

Stack Overflow's diff view is very good. I want to do this using javascript, but I don't know how to start, who can give some suggestion?
such as:
you can try google-diff-match-patch project ,this project offer robust algorithms to perform the operations required for synchronizing plain text.
Demo:http://jsfiddle.net/N6bAn/
Code:
<div class="test">
<div id="oldStr" class="text">the stackoverflow question and answer version control is very well,i want to do this use javascript,but i don't know how to start,who can give some suggestion?thanks</div>
<div id="newStr" class="text">Stack Overflow's diff view is very good. I want to do this using javascript,but i don't know how to start,who can give some suggestion?thanks</div>
</div>
<input type="button" value="GO" onclick="launch()" />
<div class="test">
<div class="text" id="outputOldStr"></div>
<div class="text" id="outputNewStr"></div>
</div>
<script type="text/javascript">
var dmp = new diff_match_patch();
function launch() {
var text1 = document.getElementById('oldStr').innerHTML;
var text2 = document.getElementById('newStr').innerHTML;
dmp.Diff_EditCost = 8;
var d = dmp.diff_main(text1, text2);
dmp.diff_cleanupEfficiency(d);
var oldStr = "", newStr = "";
for (var i = 0, j = d.length; i < j; i++) {
var arr=d[i];
if (arr[0] == 0) {
oldStr += arr[1];
newStr += arr[1];
} else if (arr[0] == -1) {
oldStr += "<span class='text-del'>" + arr[1] + "</span>";
} else {
newStr += "<span class='text-add'>" + arr[1] + "</span>";
}
}
document.getElementById('outputOldStr').innerHTML = oldStr;
document.getElementById('outputNewStr').innerHTML = newStr;
}
</script>
There are JavaScript libraries that does diff visualization. These are a few examples I found:
https://github.com/cemerick/jsdifflib
http://prettydiff.com/
I haven't tried any of them, so unfortunately I can't tell you which is most suited for you needs, but it might be worth checking them out.
Update
jsdifflib looks promising, there is a demo available that you could try.

Categories

Resources