Why is this JavaScript code not working? - javascript

Why is this code working? I want to take the input variable and getting the emails out of it. It's not working though. Can someone help me?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript">
var email = /[a-z0-9\.&%]+#(?:[a-z1-9\-]+\.)+[a-z]{2,4}/i;
var input = "hi4d#gmail.com#gmail.com text here shaagd4##fdfdg.ct hefds#4564dh-dsdgd.ly";
var testout = true;
var output;
while(testout === true)
{
var execoutput = email.exec(input);
testout = email.test(input);
if(!output) {output = '';}
if(testout === true)
{
output += "<p>An email found was: " + execoutput[0] + ".</p>";
input = input.substring(execoutput[0].length);
}
}
document.write(output);
</script>
</head>
<body>
</body>
</html>

Try this: (on jsfiddle)
var email = /[a-z0-9\.&%]+#(?:[a-z0-9\-]+\.)+[a-z]{2,4}/i;
var input = "hi4d#gmail.com#gmail.com text here shaagd4##fdfdg.ct hefds#4564dh-dsdgd.ly";
var output = '';
for (;;) {
var execoutput = email.exec(input);
if (!execoutput) {
break;
}
output += "<p>An email found was: " + execoutput[0] + ".</p>";
input = input.substring(execoutput.index + execoutput[0].length);
}
document.write(output);
Note a few problems I've corrected:
The regex did not match the 0 character in the domain part. None of your input strings contained this character in the domain part, but it was a bug nonetheless.
You can't just pull off the first N characters of the input string when N is the length of the matched string, because it may not have matched at position 0. You have to add the index of the match too, or you might match the same address multiple times.

As mentioned in the comment, the code works.
It should however be duly noted I just slapped your code straight into my current project (Yay for messing up stuff!) and it works just fine there too.
HOWEVER it does not LOOK right, nor provide the correct output I suspect you want.

Related

How do I select text between two characters in Javascript?

So I am currently trying to find out how to select text between two characters(for the example I will use a slash / )
Here is what I have so far.
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function startWhenLoaded() {
var text = $("p").text();
var secondStartingPoint, startPointOne, startPointTwo;
if (text.indexOf("/", 0) !== -1) {
//I did -1 because indexOf returns -1 if nothing is found.
/*Also, the second argument in indexOf() acts as my starting
point for searching.*/
secondStartingPoint = text.indexOf("/") + 1;
startPointOne = text.indexOf("/") + 1;
if (text.indexOf("/", secondStartingPoint) !== -1) {
startPointTwo = text.indexOf("", secondStartingPoint) + 1;
var selectedText = slice(startPointOne, startPointTwo);
$("body").append("<p>" + selectedText + "</p>");
//but nothing happens.
}
}
</script>
</head>
<body onload="startWhenLoaded()">
<p>/can I select and duplicate this?/</p>
</body>
</html>
But it doesn't do anything.
It could be achieved simply by using a regex like :
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function startWhenLoaded() {
var text = $("p").text();
var extracted = text.match(/\/(.*)\//).pop();
alert('The extracted text is :'+extracted);
}
</script>
</head>
<body onload="startWhenLoaded()">
<p>Some text here in the start /can I select and duplicate this?/ Some extra text at the end</p>
</body>
</html>
Regex is simplest and easiest way to get your solution.
use exec() function to get text between '/';
console.log(/^\/(.*)\/$/.exec('/some text, /other example//'))

How to use a For Loop to make a triangle out output of the inputted numbers in JavaScript

Hello there!
I've been a given a Task like so:
Request the user to enter a number
Check if the user input is not empty. Also, check value entered is a number
Write on the HTML document a triangle out of the numbers as follow:
E.g. output: (let’s say the user entered number 10)
Your input number is 10.
10
11 11
12 12 12
13 13 13 13
14 14 14 14 14
15 15 15 15 15 15
The triangle should have 6 rows.
Use Comments explaining how the program works
Follow Indentation for clarity purposes.
Here is what I've tried so far:
var input = prompt("Enter a number: ");
if (input.value == '' || input.value == input.defaultValue) {
alert("Either you entered a NaN or you left an empty field. \nPlease enter some number!");
}
for (input = 10; input <= 15; input++) {
var a = '';
for (var j = 10; j <= input; j++) {
var a = a + '' + input;
}
document.writeln(a + "<BR>");
}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Task Write your Own Code</title>
</head>
<body>
<h1>Task Write your Own Code</h1>
</body>
</html>
First of all, my IF statement is not working properly even if I input a string or don't leave a blank input field - the alert message still pop up;
And the result of document.writeln still printed even after alert pop's up with inputted string or empty field;
Please, someone, help me to solve this task or at least tell me what I'm doing wrong?
Thanks!
Look at the documentation for window.prompt().
Remove .value. input is the value.
Also, you aren't telling your code to not run if input is "bad".
// Be in a function so that you can return
(function() {
var input = prompt("Enter a number: ");
if (!input) {
alert("Either you entered a NaN or you left an empty field. \nPlease enter some number!");
// Get of of the function
return;
}
for (input = 10; input <= 15; input++) {
var a = '';
for (var j = 10; j <= input; j++) {
var a = a + '' + input;
}
document.writeln(a + "<BR>");
}
}());
|| input.value == input.defaultValue makes no sense since there is no such thing as input.defaultValue and, even if there was, you only need to check for an empty string. Also, input is already the response from the user so .value isn't needed.
You need to add an else condition to your if statement because even if no number is entered, your code will continue to do the looping.
Additionally, document.write() is only ever used in rare situations where you are building a new document from scratch, dynamically. It should not be used just to update an existing page's content. Instead, prepare an empty element ahead of time and when ready, update the content of that element.
Your loop configurations were a little off as well.
See other comments inline:
// Get the user's response, converted to a number
var input = parseInt(prompt("Enter a number: "), 10);
// Get a reference to the waiting output area on the page
var output = document.getElementById("output");
// Check that a number was given
if (!isNaN(input)) {
// We have a number...
// You know you need to go 6 times
for (x = 1; x < 7; x++) {
var a = '';
// And then you need to go however many times the outer loop is on
for (var j = 1; j <= x; j++) {
a += input + ' '; // You just need to write out the current input value
}
input++; // Increase the value
// Update the output area on the page
output.innerHTML += a + "<br>";
}
} else {
// We don't have a number:
alert("Either you entered a NaN or you left an empty field. \nPlease enter some number!");
}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Task Write your Own Code</title>
</head>
<body>
<h1>Task Write your Own Code</h1>
<div id="output"></div>
</body>
</html>
And, if and when you get more into String operations, you'll find that you don't even need the inner loop:
// Get the user's response, converted to a number
var input = parseInt(prompt("Enter a number: "), 10);
// Get a reference to the waiting output area on the page
var output = document.getElementById("output");
// Check that a number was given
if (!isNaN(input)) {
// We have a number...
// You know you need to go 6 times
for (x = 1; x < 7; x++) {
// Set up the string to be written and then just repeat that
// however many times the outer loop is currently on.
output.innerHTML += (input + " ").repeat(x) + "<br>";
input++; // Increase the value
}
} else {
// We don't have a number:
alert("Either you entered a NaN or you left an empty field. \nPlease enter some number!");
}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Task Write your Own Code</title>
</head>
<body>
<h1>Task Write your Own Code</h1>
<div id="output"></div>
</body>
</html>

How do I print the result of a search() method in JavaScript?

I posted a question earlier regarding a school problem I was working on. I have what I believe to be the correct function per the assignment, but I am stuck. I need to have the alert() in my code display the index position of the substring it is searching for. Everything else works but I don't know how to send that info back to a variable that I can print to the screen. My code is as follows:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Lesson 6 Application Project A</title>
<script language="JavaScript" type=text/javascript>
<!--
/*****************************************************************************
The placeholders sub and string are used to pass as arguments the
user's entry into the text box and the textarea. The variable where
is assigned the result of a method which returns the index (integer)
of the first occurence of sub (the string the program is searching for).
Start the search at the beginning of string (the text that is being searched).
Since the string is zero based, add 1 is to get the correct position of sub.
*****************************************************************************/
function search(sub, string) {
var where;
if (string.search(sub) != -1){
where = alert("Your index position is: " + where);
}
else{
where = alert("Could not find your string!");
}
}
//-->
</script>
</head>
<body>
<h3>CIW JavaScript Specialist</h3>
<hr />
<form name="myForm">
<p>
<strong>Look for:</strong>
<input type="text" name="what" size="20" />
</p>
<p>
<strong>in this string:</strong>
<textarea name="toSearch" rows="4" cols="30" wrap="virtual">
</textarea>
</p>
<p>
<input type="button" value="Search"
onclick="search(myForm.what.value, myForm.toSearch.value);" />
</p>
</form>
</body>
</html>
Try this
function search(sub, string) {
var where = string.indexOf(sub);
if (where != -1){
alert("Your index position is: " + where);
}
else{
alert("Could not find your string!");
}
}
Your where variable should be assinged to the result of the search.
function search(sub, string) {
var where = string.search(sub);
if (where != -1){
alert("Your index position is: " + (where + 1));
}
else{
alert("Could not find your string!");
}
}
My solution to my own problem was to create a variable called position and set it to receive the index position of the substring. I could then add that into my alert() and display the results to the screen. Corrected code is as follows:
function search(sub, string) {
var where;
var position = string.search(sub);
if (string.search(sub) != -1){
where = alert("Your index position is: " + position);
}
else{
where = alert("Could not find your string!");
}
}

issues with html and js

This is so bloody frustrating. I went through W2school tutorials, where bits and pieces are presented to you but it does not answer how to put it all together. I thought I understood it but when I put it into practice, nothing. Firebug is telling me that inputEmp() is not defined, but is quite obviously defined in the .js file. Can someone please tell me what minor detail I left out? Thanks First the Html, then the .js file.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="css/payroll.css" />
<title>Payroll System</title>
<script type="text/javascript" src="scripts/payroll.js"></script>
<script type="text/javascript" >
var emps = new Array();
</script>
</head>
<body>
<h1>Jackson Payroll System</h1>
<button type="button" onclick="inputEmp()">
Click here to enter employees
</button>
</body>
</html>
// payroll.js
function inputEmp() {
var inName = "";
var loopCt = 0
var tArray = new Array();
while (inName != "-1}
{
prompt inName = prompt("Please enter your name (enter -1 to finish)",
"Employee Name");
if (inName == "-1") { break; }
if (inName==null || inName=="")
{
alert("Blank names are not allowed. To exit enter '-1'.");
}
else
tArray[loopCt++] = inName;
{
}
return tArray;
}
Yes, you forgot to close the brace { of while loop before return statement. and the quotes is not closed in condition.
Try this
function inputEmp() {
var inName = "";
var loopCt = 0
var tArray = new Array();
while (inName != "-1"} {
prompt inName = prompt("Please enter your name (enter -1 to finish)","Employee Name");
if (inName == "-1") { break; }
if (inName==null || inName=="")
{
alert("Blank names are not allowed. To exit enter '-1'.");
}
else
tArray[loopCt++] = inName;
{
}
}
return tArray;
}
There is a lot of problem in your code:
var loopCt = 0 should look like this var loopCt = 0;
while (inName != "-1} should look like this while (inName != "-1)
prompt inName = prompt... should look like this inName = prompt...
There is an empty { } under the else statement
Here is a jsfiddle that shows you the corrected code.

search() function of Javascript does not behave properly

I don't know why search() function returns 0 for any input with SPECIAL CHARACTER, I wanted to find position of 1st occurrence of special character. When I am hardcoding the value for search() method it is working fine, but when I am taking value from text box it is not working properly.
Following is my HTML code:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script type="text/javascript" src="jquery-1.6.4.min.js"></script>
<script type="text/javascript" src="test.js"></script>
</head>
<body>
<input type="text" id="txt" onkeyup="return checkLength();"/>
<input type="button" id="btn" value="Verify" onclick="getValue()"/>
</body>
</html>
Following is the script where I have implemented the use of search() of Javascript, but don't know why I am getting 0 value for any input. Actually I wanted to find the position of first special character occurrence.
$(document).ready(function() {
$('#btn').attr('disabled',true);
$("#txt").bind({
paste : function(){
$('#btn').attr('disabled',false);
checkLength();
},
cut : function(){
checkLength();
}
});
});
function checkLength(){
var txtLength = $("#txt").val().length;
var banTxt = document.getElementById("txt").value;
if (txtLength != 0) {
if(isAlphaNumeric(document.getElementById("txt").value)) {
$('#btn').attr('disabled',false);
} else {
var str=banTxt;
//Here I am using search() to find position of Special Character.
var n=banTxt.search(/[^a-zA-Z ]/g);
alert("position of special char is: " + n);
var preTxt = banTxt.substring(0,(txtLength - 1));
var preTxtLength = preTxt.length;
alert("Special characters are not allowed!");
if(preTxtLength == 0){
$('#btn').attr('disabled',true);
document.getElementById("txt").value = "";
}else if(preTxtLength != 0){
document.getElementById("txt").value = preTxt;
$('#btn').attr('disabled',false);
}
}
} else {
$('#btn').attr('disabled',true);
}
}
function isAlphaNumeric(inputString) {
return inputString.match(/^[0-9A-Za-z]+$/);
}
function getValue(){
var txtValue = document.getElementById("txt").value;
alert("Value submitted is: " + txtValue);
}
var n=banTxt.search(/[^a-zA-Z ]/g);
I tried with string with special characters like 123#4$5 , 12#4 , etc. and I am getting alert as position of special char is: 0
That's just what your regex matches: No alphabet characters and no blanks - that includes digits. In contrast, your isAlphaNumeric function matches against /^[0-9A-Za-z]+$/ - you probably want to align them with each other.
Actually i have used the following line var n=banTxt.search(/[^a-zA-Z ]/g); for getting the position of special char, at the same time please note that i have used onkeyup event so if i am copy pasting the code i.e first ctrl then v, ctrl + v then ctrl itself is keyup event i think this might be the reason i am getting 0 as position of special char, as after pressing ctrl no text is pasted but onkeyup event is triggered.
I am looking for the solution of it.

Categories

Resources