multiple matches in regex - javascript

Hi I am trying to get the following javascript code to work. When I am typing a line containing all three names
fever, nightsweats and nocturia - I want an alert window to come on reminding me that those three in combination represent a dangerous sign. what am I doing wrong? thanks so much in advance!!!
<html>
<script type="text/javascript">
function show_prompt() {
var q = prompt("Please enter your name", "");
var myRegExp1 = ^ ( ? = . * fever)( ? = . * night sweats)( ? = . * nocturia);
var myRegExp2 = /fever,weight-loss,nocturia|weight-loss,fever,nocturia|nocturia,weight-loss,fever/
var string1 = q;
var string2 = q;
var matchPos1 = string1.search(myRegExp1);
var matchPos2 = string2.search(myRegExp2);
if (matchPos1 != -1) {
alert("bingo" + matchPos1);
}
if (matchPos2 != -1) {
alert("symptoms" + matchPos2);
}
}
</script>
<body>
<input type="button" onclick="show_prompt()" value="Show prompt box" />
</body>
</html>

For one, you have a syntax error :
var myRegExp1 = ^ ( ? = . * fever)( ? = . * night sweats)( ? = . * nocturia);
Needs to be
var myRegExp1 = /^ ( ? = . * fever)( ? = . * night sweats)( ? = . * nocturia)/;

If I understand correctly, I think this is what you want. Please test it here.
function show_prompt() {
var q = prompt("Please enter your name", "");
var myRegExp = /(fever|weight-loss|nocturia),(fever|weight-loss|nocturia),(fever|weight-loss|nocturia)/;
var string = q;
var matchPos = string.search(myRegExp);
if (matchPos != -1) {
alert("symptoms" + matchPos);
}
}

Related

How do I get the substr after a word or index in JavaScript?

I have the following element below in my DOM.
<div id="klarna-checkout-container" style="overflow-x: hidden;">
<script type="text/javascript">
/* <![CDATA[ */
(function(w,k,i,d,n,c,l){
w[k]=w[k]||function(){(w[k].q=w[k].q||[]).push(arguments)};
l=w[k].config={
container:w.document.getElementById(i),
ORDER_URL:'https://checkout-eu.playground.klarna.com/yaco/orders/1234-fa14-4a0f-bf2d-5678',
AUTH_HEADER:'KlarnaCheckout 76c9bumqmkt8oy7wcpnr6',
LOCALE:'sv-SE',
ORDER_STATUS:'checkout_incomplete',
MERCHANT_TAC_URI:'https://demo.krokedil.se/klarnacheckout/terms/',
MERCHANT_NAME:'K500956',
GUI_OPTIONS:[],
ALLOW_SEPARATE_SHIPPING_ADDRESS:true,
PURCHASE_COUNTRY:'swe',
PURCHASE_CURRENCY:'SEK',
TESTDRIVE:true,
CHECKOUT_DOMAIN:'https://checkout-eu.playground.klarna.com',
BOOTSTRAP_SRC:'https://a.klarnacdn.net/kcoc/6788-345/checkout.bootstrap.js',
CLIENT_EVENT_HOST:'https://evt.playground.klarna.com'
};
n=d.createElement('script');
c=d.getElementById(i);
n.async=!0;
n.src=l.BOOTSTRAP_SRC;
c.appendChild(n);
try{
((w.Image && (new w.Image))||(d.createElement && d.createElement('img'))||{}).src =
l.CLIENT_EVENT_HOST + '/v1/checkout/snippet/load' +
'?sid=' + l.ORDER_URL.split('/').slice(-1) +
'&order_status=' + w.encodeURIComponent(l.ORDER_STATUS) +
'&timestamp=' + (new Date).getTime();
}catch(e){}
})(this,'_klarnaCheckout','klarna-checkout-container',document);
/* ]]> */
</script>
</div>
I want to get the value after the word called AUTH_HEADER:. So the value I am looking for is KlarnaCheckout 76c9bumqmkt8oy7wcpnr6
I tried using the code below but it needs improvement.
<script>
$(document).ready(function() {
var get_klarna_checkout_container = $('#klarna-checkout-container').text().trim();
var klarna_checkout_container_index = get_klarna_checkout_container.indexOf('AUTH_HEADER:');
var klarna_checkout_container_index_2 = get_klarna_checkout_container.substr(klarna_checkout_container_index, 289);
console.log(klarna_checkout_container_index_2);
});
</script>
The output of console.log above is:
AUTH_HEADER:'KlarnaCheckout 76c9bumqmkt8oy7wcpnr6',
LOCALE:'sv-SE',
ORDER_STATUS:'checkout_incomplete',
MERCHANT_TAC_URI:'https://demo.krokedil.se/klarnacheckout/terms/',
MERCHANT_NAME:'K500956',
GUI_OPTIONS:[],
ALLOW_SEPARATE_SHIPPING_ADDRESS:true,
PURCHASE_CO
I am aiming for KlarnaCheckout 76c9bumqmkt8oy7wcpnr6
The problem with my code above is that it prints a lot of string instead of just adding characters from what I added in substr method.
Any help is appreciated. Thanks.
I went the regex route. The line to look for is
var found = klarna_checkout_container_index_2.match(/AUTH_HEADER:'(.+)'/);
var get_klarna_checkout_container = $('#klarna-checkout-container').text().trim();
var klarna_checkout_container_index = get_klarna_checkout_container.indexOf('AUTH_HEADER:');
var klarna_checkout_container_index_2 = get_klarna_checkout_container.substr(klarna_checkout_container_index, 289);
var found = klarna_checkout_container_index_2.match(/AUTH_HEADER:'(.+)'/);
console.log(found[1]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<div id="klarna-checkout-container" style="overflow-x: hidden;">
<script type="text/javascript">
/* <![CDATA[ */
(function(w,k,i,d,n,c,l){
w[k]=w[k]||function(){(w[k].q=w[k].q||[]).push(arguments)};
l=w[k].config={
container:w.document.getElementById(i),
ORDER_URL:'https://checkout-eu.playground.klarna.com/yaco/orders/1234-fa14-4a0f-bf2d-5678',
AUTH_HEADER:'KlarnaCheckout 76c9bumqmkt8oy7wcpnr6',
LOCALE:'sv-SE',
ORDER_STATUS:'checkout_incomplete',
MERCHANT_TAC_URI:'https://demo.krokedil.se/klarnacheckout/terms/',
MERCHANT_NAME:'K500956',
GUI_OPTIONS:[],
ALLOW_SEPARATE_SHIPPING_ADDRESS:true,
PURCHASE_COUNTRY:'swe',
PURCHASE_CURRENCY:'SEK',
TESTDRIVE:true,
CHECKOUT_DOMAIN:'https://checkout-eu.playground.klarna.com',
BOOTSTRAP_SRC:'https://a.klarnacdn.net/kcoc/6788-345/checkout.bootstrap.js',
CLIENT_EVENT_HOST:'https://evt.playground.klarna.com'
};
n=d.createElement('script');
c=d.getElementById(i);
n.async=!0;
n.src=l.BOOTSTRAP_SRC;
c.appendChild(n);
try{
((w.Image && (new w.Image))||(d.createElement && d.createElement('img'))||{}).src =
l.CLIENT_EVENT_HOST + '/v1/checkout/snippet/load' +
'?sid=' + l.ORDER_URL.split('/').slice(-1) +
'&order_status=' + w.encodeURIComponent(l.ORDER_STATUS) +
'&timestamp=' + (new Date).getTime();
}catch(e){}
})(this,'_klarnaCheckout','klarna-checkout-container',document);
/* ]]> */
</script>
</div>
I think function substr is wrong.
string.substr(beginIndex, length);
If you want to get only 'KlarnaCheckout 76c9bumqmkt8oy7wcpnr6' Please use:
var klarna_checkout_container_index = get_klarna_checkout_container.indexOf('AUTH_HEADER:') + 12;
var klarna_checkout_container_index_2 = get_klarna_checkout_container.substr(klarna_checkout_container_index, 36);
//This is one way to do it. Hope it helps.
let div = document.querySelector("#klarna-checkout-container script").innerText,
str = div.split(","),
authHeader;
for(let index in str){
let temp = str[index].split(":");
if(temp[0].trim() === "AUTH_HEADER"){
authHeader = temp[1].trim();
}
}
If you split the text with the key + ":'", second item of splitted index will contain the value at index 0 and then you can split it again with "'" or "'," which first element of its result will contain the value you are looking for.
const getHeaderValue = function (text, toFind) {
return text.split(toFind + ":'")[1].split("'")[0];
};
$(document).ready(function() {
var container = $('#klarna-checkout-container').text().trim()
console.log(getHeaderValue(container, 'AUTH_HEADER'))
})
Based on what your code currently outputs, just do this:
if (typeof klarna_checkout_container_index_2 == "string") {
klarna_checkout_container_index_2 = JSON.parse(klarna_checkout_container_index_2);
}
console.log(klarna_checkout_container_index_2["AUTH_HEADER"]);

How to remove innerHTML value to be shown initially

I am trying to create a multiplication table in JavaScript. The user is prompted to provide the Table number (1 to 10) after which all the question marks ('?') are replaced with that number. The user then needs to enter the answers in all the provided text fields. Finally, the user will have the option to check the answer (i.e. whether it is right or wrong).
When I run my code. After entering the user data to prompt it shows Incorrect infront of each textfield and the user entered value just before the Check answers button. How can I remove them to be shown initially.
Output:
My code:
function result() {
var value = document.getElementById("a1").value;
var checkMessageSpan1 = document.getElementById("checkMessage1");
var checkMessageSpan2 = document.getElementById("checkMessage2");
var r = x * 1;
if (value == x) {
checkMessageSpan1.innerHTML = "<span style=\"color:green\">"+"Correct!";
}else{
checkMessageSpan1.innerHTML = "<span style=\"color:red\">"+"Incorrect!";
}
var value = document.getElementById("a2").value;
var r = x * 2;
if (value == r) {
checkMessageSpan2.innerHTML = "<span style=\"color:green\">"+"Correct!";
}else{
checkMessageSpan2.innerHTML = "<span style=\"color:red\">"+"Incorrect!";
}
</script>
<button onClick="alert_field()"> Generate Question</button><br><br>
<p id="s1">
? x 1 = <input type="text" id="a1"><span id="checkMessage1"></span><br>
? x 2 = <input type="text" id="a2"><span id="checkMessage2"></span><br>
</p><br><br>
<p id="a"></p>
Check answers
For replacing all special characters, you may leverage regular expressions in js
var res=str.replace(/[^a-zA-Z0-9]/g,x); instead of
var res = str.replace("?",x);
More on Regular expressions in JS https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
Try to add this code:
var value = document.getElementById("a1").value;
if (checkMessageSpan1.style.display === "none") {
checkMessageSpan1.style.display = "inline-block";
} else {
checkMessageSpan1.style.display = "none";
}
var value = document.getElementById("a2").value;
if (checkMessageSpan2.style.display === "none") {
checkMessageSpan2.style.display = "inline-block";
} else {
checkMessageSpan2.style.display = "none";
}

Removing a range starting occurrence with specified place

I need to define the text area to delete from 4th occurrence of (_) and preserve the extension.
before 12_345_678_900_xxxxxxxxxxxxxxx.jpg after 12_345_678_900.jpg,
before 34_567_890_123_xxxxxxxx_xxxxx_xxxxxxxxxxx.jpg
after 34_567_890_123.jpg
Is it possible?
One solution is to find the nth occurence and then use substring.
var one='12_345_678_900_xxxxxxxxxxxxxxx.jpg'; // 12_345_678_900.jpg
function nth_occurrence (string, char, nth) {
var first_index = string.indexOf(char);
var length_up_to_first_index = first_index + 1;
if (nth == 1) {
return first_index;
} else {
var string_after_first_occurrence = string.slice(length_up_to_first_index);
var next_occurrence = nth_occurrence(string_after_first_occurrence, char, nth - 1);
if (next_occurrence === -1) {
return -1;
} else {
return length_up_to_first_index + next_occurrence;
}
}
}
console.log(one.substring(0,nth_occurrence(one,'_',4))+one.substring(one.indexOf('.')));
Sure, split by "_" and then join back the data you want:
var str = "12_345_678_900_xxxxxxxxxxxxxxx.jpg";
str = str.split("_").slice(0,4).join("_") + "."+ str.split(".").slice(-1)
console.log(str)
Regular Expressions are great for this sort of scenario:
const data1 = '12_345_678_900_xxxxxxxxxxxxxxx.jpg'
const data2 = '34_567_890_123_xxxxxxxx_xxxxx_xxxxxxxxxxx.jpg'
const re = /^([^_]+_[^_]+_[^_]+_[^_]+).*(.jpg)$/;
var test1 = data1.replace(re, '$1$2');
var test2 = data2.replace(re, '$1$2');
Try it out: https://jsfiddle.net/648xt3qq/
There are probably a few different regular expression approaches that would get the job done
Maybe this works for you:
function clean() {
var el = document.getElementById('area');
el.value = el.value.replace(/^(.*?_.*?_.*?_.*?)(_.*?)(\..*?.*)$/gmi, '$1$3');
}
<form action="">
<textarea cols="50" rows="4" id="area">12_345_678_900_xxxxxxxxxxxxxxx.jpg
34_567_890_123_xxxxxxxx_xxxxx_xxxxxxxxxxx.jpg</textarea><br />
<input type="submit" onclick="clean(); return false;" />
</form>

How to get specific radio value from PHP

I'm not getting the right value from my radio buttons on my 'Thank You' page.
I want that after my user end the payment and he get redirected to the thank you page some values from the filled form to be posted there. And I have archive just that with this script on the form.php file:
<script type="text/javascript">
function CookieTheFormValues() {
var cookievalue = new Array();
var fid = document.getElementById(FormID);
for (i = 0; i < fid.length; i++)
{
var n = escape(fid[i].name);
if( ! n.length ) { continue; }
var v = escape(fid[i].value);
cookievalue.push( n + '=' + v );
}
var exp = "";
if(CookieDays > 0)
{
var now = new Date();
now.setTime( now.getTime() + parseInt(CookieDays * 24 * 60 * 60 * 1000) );
exp = '; expires=' + now.toGMTString();
}
document.cookie = CookieName + '=' + cookievalue.join("&") + '; path=/' + exp;
return true;
}
</script>
And than by putting this script on the thank you page :
<?php
$CookieName = "PersonalizationCookie";
$Personal = array();
foreach( explode("&",#$_COOKIE[$CookieName]) as $chunk )
{
list($name,$value) = explode("=",$chunk,2);
$Personal[$name] = htmlspecialchars($value);
}
?>
So far so good I get all right values from other inputs but from radios I get always the last in class name value? This mean for eg if I have this code:
<input type="radio" name="emotion" id="basi" value="Basic Pack" />
<input type="radio" name="emotion" id="deli" value="Deluxe Pack" />
<input type="radio" name="emotion" id="premi" value="Premium Pack"/>
And in the Thank you page I put this code for eg
Thank you for chosing <?php echo(#$Personal["emotion"]); ?>
I get always this Thank you for choosing Premium Pack even when i check the basic or deluxe radio why this?
Your loop:
for (i = 0; i < fid.length; i++)
{
var n = escape(fid[i].name);
if( ! n.length ) { continue; }
var v = escape(fid[i].value);
cookievalue.push( n + '=' + v );
}
will push all three of the radios into your cookie value. Each one will overwrite the previous, because they have the same name. So ultimately you're left with the value 'Premium Pack' mapped to the "emotion" name. You need to check if the radio is selected before you push the val, maybe something like:
for (i = 0; i < fid.length; i++)
{
var n = escape(fid[i].name);
if( ! n.length ) { continue; }
var v = escape(fid[i].value);
// Only push in the selected emotion radio button
if (n == "emotion") {
if (fid[i].checked == true) cookievalue.push( n + '=' + v );
}
else cookievalue.push( n + '=' + v );
}

Captcha JavaScript, should work but

It just wont generate random numbers and input them in span id "broj1" and "broj2". This should work and i cant find any obvious error cause im still new to this. Thanks for help in advance :)
function potvrda(){
var odgovor = document.getElementById("odgovor").value;
var broj1 = parseInt(document.getElementById("broj1").innerHTML);
var broj2 = parseInt(document.getElementById("broj2").innerHTML);
var zbroj = broj1 + broj2;
if (odgovor == null || odgovor ==""){
alert("Molimo unesite zbroj");
return false;
}
else if(odgovor != zbroj){
alert("Molimo unesite ispravan Broj");
}
else{
document.getElementById("status").innerHTML = "processing";
docuemnt.getElemtntById("odgovor").innerHTML = "";
}}
function randomNums(){
var ran_num1 = Math.floor(Math.random() * 10) +1 ;
var ran_num2 = Math.floor(Math.random() * 10) +1 ;
document.getElementById("broj1").innerHTML = rand_num1;
document.getElementById("broj2").innerHTML = rand_num2;
}
</script>
<form method="post" onsubmit="return potvrda();">
Zbrojite:
<span id="broj1"></span> + <span id="broj2"></span>=</br>
<input type="text" id="odgovor" size="50" /> </br>
You are defining var ran_num1 and var ran_num2, but then you are trying to set the innerHTML of the elements to rand_num1 and rand_num2. You're missing a "d". This fiddle is working for me: http://jsfiddle.net/68NKQ/

Categories