The following code looks for the name of a person in a message that they have entered using the indexOf method.
However it is returning the not present result even when the name is present. If I only Darren as the cardMessage it works.
Can anyone point out what is wrong.
<%
firstName = "Darren"
cardMessage = "Is Darren in the message?"
cardMessage = CleanX(cardMessage)
firstName = UCase(firstName)
cardMessage = UCase(cardMessage)
Function CleanX(strString)
Set regEx = New RegExp
regEx.Pattern = "[^a-z0-9 ]+"
regEx.IgnoreCase = True
regEx.Global = True
CleanX = regEx.Replace(strString, "")
End Function
%>
<p><%=cardMessage%></p>
<p><%=firstName%></p>
Click Here
<script type="text/javascript">
s1 = new String("<%=firstName%>")
s2 = new String("<%=cardMessage%>")
function check_message()
{
var purchaser=s1;
var purchaser_ok=purchaser.indexOf(s2);
if (purchaser_ok==-1)
{
confirm('Name is NOT in message');
}
else
alert('Name is in message');
}
</script>
You're doing it backwards. It should be
var purchaser_ok = s2.indexOf(purchaser);
The ".indexOf()" function checks to see whether the argument you pass into it is in the string that's used as the receiver (the context object; that is, the string before the "." when you call it).
You have it backwards.
s2.indexOf(purchaser)
Related
here is the regex demo
the REGULAR EXPRESSION
getObj\("Frm_Logintoken"\).value = "(.*)";
this the TEST STRING
getObj("Frm_Logintoken").value = "3";
i want to get that number only "3" without quotes
it's in the Group 1 of the matches but i don't know how to get it from that group .
i can't var myString = "something format_abc";
because i am doing this to get the value that i don't know !!
And testing this in console results
var test = /getObj("Frm_Logintoken").value = "(.*)";/g
undefined
console.log(test1);
undefined
undefined
the same question but in a different way and detailed still unanswered
i have tried
getObj\("Frm_Logintoken"\).value = "(.*)";`.match(/getObj\("Frm_Logintoken"\).value = "(.*)";/)[1]
it give me this "(.*)" not the wanted value !!!
some notes
1-that value isn't static
2- i want to make the code works automatic so fetching the line "getObj("Frm_Logintoken").value = "3";"
from the page code manually is unwanted thing.
3- i want to make an auto login script without any User intervention.
4- if you still don't understand the question see the links pls
thanks
You can access group by accessing index of matched value
let str = `getObj("Frm_Logintoken").value = "3";`
let op = str.match(/getObj\("Frm_Logintoken"\).value = "(.*)";/)
console.log(op[1])
you must declare the string first !
so if you are trying to get the value from the current page html code you can just
let str = document.body.innerHTML;
let pattern =/\bgetObj\("Frm_Logintoken"\)\.value = "([^"]+)";/;
console.log(str.match(pattern)[1]);
and if you are trying to fetch the html string from other page using something like XMLHttpRequest
you can do this
let str = (http.responseText);
the full code :
const http = new XMLHttpRequest();
const url = 'http://page/';
http.open('get', url, false);
http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
http.onreadystatechange = function ()
{
if(http.readyState === 4)
{
if(http.status === 200 || http.status == 0)
{
let str = (http.responseText);
let pattern =/\bgetObj\("Frm_Logintoken"\)\.value = "([^"]+)";/;
let results = str.match(pattern)[1];
console.log(results);
}
}
}
http.send();
Hope you understand and make a Clearer question next time and write your really point of the question and the use of the wanted fix .
var v= document.getElementById('btn');
v.addEventListener('click', action);
var selection = document.getElementById('inputGroupSelect01');
function action(e) {
document.getElementById('inputGroupSelect01');
console.log(selection.value);
var b = parseInt("selection.value");
console.log(typeof(b));
if (b === 2) {
console.log("congo number is 1");
}
else {
console.log('not');
}
}
This line is wrong:
var b = parseInt("selection.value");
You are trying the parse the literal string "selection value" into an integer, instead of the value of the field value of whatever selection refers to.
Should be:
var b = parseInt(selection.value);
change var b = parseInt("selection.value"); to var b = parseInt(selection.value);
since you are parsing the value which is string but string also should be integer like so parseInt('1') will work but parseInt('demo') will not work. so you are doing like this parseInt("selection.value"); which will never work.
The issue seems to be with this line var b = parseInt("selection.value"); It will give an undefined
Replace that line with this var b = parseInt(selection.value,10)
I'm fairly new to Javascript, and am confused on something. Why can't the command "println("..."); be called as a variable such as: var num = println("...");. I could be wrong, and if you are able to, I'd be happy to know how. But after some testing it seems like I can't. My test code is:
function start() {
var SENTINEL = "1 1";
var rollOne = Randomizer.nextInt(1, 6);
var rollTwo = Randomizer.nextInt(1, 6);
var num = println(rollOne + rollTwo);
if(num == SENTINEL) {
println("You did it");
}
}
All it's supposed to do is give to random numbers in a # # form and, if it sees that the numbers are 1,1, it will give a message. It wont give the message and can't seem to view the variable "num" as an actual variable. But when I change the variable num to simply asking the user for a number:
function start() {
var SENTINEL = -1;
var rollOne = Randomizer.nextInt(1, 6);
var rollTwo = Randomizer.nextInt(1, 6);
var num = readInt("Enter number");
if(num == SENTINEL) {
println("You did it");
}
}
And type in -1, it triggers the sentinel, thus promptly displaying the message. This is a really roundabout way to ask a simple question but I hope I can get some help. Thank you :)
Why can't the command "println("..."); be called as a variable such as: var num = println("...");
[...] It wont give the message and can't seem to view the variable
If the value returned is unusable, it is most likely undefined; i.e. The function println doesn't explicitly return anything.
In your case, you could try something like this:
var printInt = function(num) { println(num); return num; }
Note, println isn't part of the standard JavaScript language. For modern web browsers, it can be adapted to use (console.log(...)).
var printInt = function(num) { console.log(num); return num; }
And then to adapt to your code:
var num = printInt(rollOne + rollTwo);
But this still won't validate because you're comparing against "1 1" whereas your logic will return 2. JavaScript (as well as many other languages) implicitly uses addition when supplied with two numbers, but concatenation when supplied with at least one string.
var SENTINEL = "1 1"; // <---- String!
var SENTINEL = -1; // <---- Number!
So you should consider something like this instead (renamed accordingly):
var printRolls = function(text) { println(text); return text; }
var rolls = printRolls(rollOne + " " + rollTwo);
if(rolls == SENTINEL) {
println("You did it");
}
Or to simplify it a bit:
if(printRolls(rollOne + " " + rollTwo) == SENTINEL)
println("You did it");
It is possible that println doesn't return the string that is passed into. In that case, you can use
if (SENTINEL === rollOne + " " + rollTwo)
to format the string and properly test equality.
In JavaScript it is possible to assign the return value from any function to a variable similar to how you've done it:
var anyVariable = anyFunction();
But, some functions return the value undefined. Or they return a number, or an array, or...whatever.
I imagine your println() function prints the value you pass to it somewhere (on the screen? to the console?) and then returns undefined. Or if it is returning the printed value it is in a format different to what you have used in your SENTINEL variable. So then when you try to compare that with SENTINEL it won't be equal.
To fix your original function, assign the sum of the rolls to a variable, then print and test that:
function start() {
var SENTINEL = 2;
var rollOne = Randomizer.nextInt(1, 6);
var rollTwo = Randomizer.nextInt(1, 6);
var num = rollOne + rollTwo;
println(num);
if(num == SENTINEL) {
println("You did it");
}
}
EDIT: if you want the println() to display a string like "1 1" or "3 5" to show what each of the two rolls were then do this:
println(rollOne + " " + rollTwo);
That is, create a new string that is the result of concatenating rollOne's value with a single space and then rollTwo's value.
I've done some digging on the above topic but am now more confused than when I started.
I have a unit converter that I'm working on.
It's working fine as a base model but I'm now trying to make it more modular.
There are many units and many conversions.
My plan is to have a function that determines what type of conversion is required, temperature, area etc etc, that can then call the appropriate function to carry out the math.
I'm very new to JS which isn't helping matters as it could be a simple mistake that I'm making but it's just as likely that I'm getting huge errors.
I think the problem is passing the object to the next function and then using it.
I've played with the code a great deal and tried many different suggestions online but still no success.
here is my code:
<script type="text/javascript">
function Convert(from, to, units, res){
this.from = from;
this.to = to;
this.units = units;
this.res = res;
}
Convert.convertUnits = function(){
var measurementType = $(".from option:selected").attr("class");
var result = "invalid input";
var input = parseInt(this.units.val());
if(measurementType == "temp"){
var test = new Convert($("#from"), $("#to"), $("#units"), $("#result"));
test.convertTemp();
console.log('Did we get this far?!?! ::', measurementType);
}
console.log('or not???? ::', measurementType);
}
Convert.prototype.convertTemp = function(){
var result = "invalid input";
var input = parseInt(this.units.val());
var f = this.from.val();
var t = this.to.val()
if(!isNaN(input)) {
if(f == "degC"){
if(t == "degF"){
result = input * 1.8 + 32;
}
if(t == "kelvin"){
result = input + 273.15;
}
}
}
console.log('Parsed input is', input, "and result is", result);
this.res.val(result);
return result;
}
//var calcTempTest = new Convert($("#from"), $("#to"), $("#units"), $("#result"));
//var test = new Convert($("#from"), $("#to"), $("#units"), $("#result"));
$("#btnConvert").click.convertUnits();
</script>
The first obvious problem is this line:
$("#btnConvert").click.convertUnits();
This tries to call a convertUnits() method defined on the click method of the jQuery object returned by $("#btnConvert"). There is no such method, so you get'll get an error about how click has no method 'convertUnits'.
What you want to be doing there is binding the convertUnits() function as a click handler, which you do by passing it to the .click() method as an argument:
$("#btnConvert").click(Convert.convertUnits)
It doesn't make sense to have declared convertUnits() as a property of Convert(), though, so (although it will work as is) I'd change it to just be:
function convertUnits() {
// your code here
}
$("#btnConvert").click(convertUnits);
The only other thing stopping the code working is that on this line:
var input = parseInt(this.units.val());
...you use this assuming it will be a Convert object with a units property but you haven't yet created a Convert object - you do that inside the if(measurementType == "temp") block with this line:
var test = new Convert($("#from"), $("#to"), $("#units"), $("#result"));
So move that line to the beginning of the function and then use test instead of this:
function convertUnits(){
var test = new Convert($("#from"), $("#to"), $("#units"), $("#result"));
var measurementType = $(".from option:selected").attr("class");
var result = "invalid input";
var input = parseInt(test.units.val());
if(measurementType == "temp"){
test.convertTemp();
console.log('Did we get this far?!?! ::', measurementType);
}
console.log('or not???? ::', measurementType);
}
Working demo: http://jsfiddle.net/jT2ke/
Some unrelated advice: parseInt() doesn't really make sense for a number to feed into your converter, because the user might want to enter decimal values. You can use parseFloat() instead, or the unary plus operator:
var input = +test.units.val();
But if you want parseInt() it is generally recommended to pass it a second argument to specify the radix:
var input = parseInt(test.units.val(), 10);
...because otherwise if the input text has a leading zero some browsers will assume the value is octal rather than base ten. (parseFloat() and the unary plus don't have that issue.)
I think you should not implement the method convertUnits inside Convert object. And the new code will look like the following:
convertUnits = function(){
var measurementType = $(".from option:selected").attr("class");
var result = "invalid input";
if(measurementType == "temp"){
var test = new Convert($("#from"), $("#to"), $("#units"), $("#result"));
test.convertTemp();
console.log('Did we get this far?!?! ::', measurementType);
}
console.log('or not???? ::', measurementType);
}
Now you can initiate the convertUnits on the button click:
$("#btnConvert").click(function(){new convertUnits()});
i want javascript code to check whether my input text is in specific format as AS0301-12345
<apex:inputText id="searchText" value="{!searchText}" onmousemove="checkingstring(this)"/>
<script>
function checkingstring(searchText){
var pattern = "([a-zA-Z](2)[0-9](4)-[0-9](5))"; /// is it correct
var regexp = new System.Text.RegularExpressions.Regex(pattern);
var userInput = "(123) 555-1243";
if (!regexp.IsMatch($component.searchText))
{
alert("The syntax is always as follows: AANNNN-NNNNN (A= Alpha/Letter; N= Number) i.e.FL0301-12345</b>");
}
}
</script>
Your JS function should look more like this:
function checkingstring(inputElem) {
var regex = /^[A-Z]{2}[0-9]{4}-[0-9]{5}$/i;
var searchText = inputElem.value;
if (searchText.length && !regex.test(searchText)) {
alert('The syntax is always as follows: AANNNN-NNNNN \n' +
'(A: Alpha/Letter; N: Number), e.g. FL0301-12345');
}
}
You should probably also change the onmousemove to something more meaningful, like onblur maybe.
Take a look at this short demo.
This is how I'd do it. There is a lot of functionality you can squeeze into shorthand. Changed onMouseMove to onChange so instead of checking whenever the mouse moves it should check when an edit of searchText completes.
<apex:inputText id="searchText" value="{!searchText}" onChange="checkingstring(this)"/>
<script>
function checkingstring(searchText){
var regexp = /^[A-Z]{2}\d{4}-\d{5}$/i; //AANNNN-NNNNN A = Capital N = Number
if (!regexp.exec(searchText.value)) {
alert("The syntax is always as follows: AANNNN-NNNNN (A= Alpha/Letter; N= Number) i.e.FL0301-12345</b>");
}
}
</script>
got some ideas from w3schools js regexp page.