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!");
}
}
Related
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>
I'm trying to make a program where if you for example type in "less" in the textarea the output should show "<". What is the best way to do this?
This is how far I've gotten:
<!doctype html>
<html lang="en">
<head>
<title>Group 7 - Deckcode to JavaScript</title>
</head>
<body>
<h1>Group 7 - Deckcode to JavaScript</h1>
<p>Input your deckode below:</p>
<textarea id="myTextarea"></textarea>
<button type="button" onclick="myFunction()">Translate</button>
<p id="demo"></p>
<script>
function myFunction() {
var input
if (myTextarea == "less") {
console.log("<");
}
}
</script>
</script>
</body>
</html>
You're trying to fish values out of the DOM incorrectly. Use document.getElementById to locate the element in the DOM, and take its value for the value you require.
function myFunction() {
var textAreaValue = document.getElementById("myTextarea").value;
if (textAreaValue == "less") {
console.log("<");
}
}
I suggest using an object like this:
var translations = {};
translations["less"] = "<";
translations["greater"] = ">";
And then in your function you do like this:
function myFunction() {
var value = document.getElementById("myTextarea").value;
console.log(translations[value] ? translations[value] : "No translation found");
}
It would also be easy to add more translations e.g. based on data from a database or similar.
as and alternative to IF-condition, you can use
if (textAreaValue.indexOf("less") > -1) {
console.log("<");
}
so if the text area contains "less" text then the console prints "<"
indexOf method
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.
I am trying to make a function to split a sentence into words then split the words into characters and capitalize the first letter of each word. Yes it's homework and after many tries I can not get it to work. One thing tripping me up is using split() twice.
<!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">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<head>
<title>Sentence Case Conversion</title>
<script type= "text/javascript">
/* <![CDATA[ */
/* ]]> */
</script>
</head>
<body>
<form name= "convertText">
<p>Enter text to convert to sentence case:</p>
<input type ="text" size ="120" name="userInput">
</br>
</br>
<input name= "Submit" onclick= "sentenceCase()" value= "Convert Text" type= "button">
</form>
</br>
</br>
</br>
<form name= "ouputText">
<p>Here is your converted text:</p>
<input type="text" size="120" name="result">
<script type= "text/javascript">
/* <![CDATA[ */
function sentenceCase() {
var userInput = document.forms[0].userInput.value; //get user input
var wordArray = userInput.split(" "); //split user input into individual words
for (var i=0; i<wordArray.length; i++) {
var characterArray = wordArray[i].split("");
characterArray[0].toUpperCase();
wordArray[i]=characterArray.join;
}
/* ]]> */
</script>
</body>
</html>
You're close:
> characterArray[0].toUpperCase();
That returns a value, it doesn't modify it in place
> wordArray[i]=characterArray.join;
join is a method, you have to call it. Also, it returns a value, it doesn't modify anything in place. You might consider using substring instead, but with the array you have:
var firstChar = characterArray.shift().toUpperCase();
var newWord = firstChar + characterArray.join('');
should do the trick.
toUpperCase() can't modify your variable in place; it returns the capitalized string. So:
characterArray[0] = characterArray[0].toUpperCase();
... but you could just use charAt() and substring(), too:
wordArray[0] = wordArray[0].charAt(0).toUpperCase() + wordArray[0].substring(1);
... and then you have to actually call join():
wordArray[i] = characterArray.join();
... and you'd probably want to pass that an empty string, or it'll default to a comma as a separator.
The fun way is 'hello world this is camel case'.replace(/\s(\S)/g, function($0, $1) { return $1.toUpperCase(); }), though.
Factor out the common elements into understandable pieces of code:
function toCamelCase(sentence) {
var words = sentence.split(" ");
var length = words.length;
for (var i = 1; i < length; i++)
words[i] = capitalize(words[i]);
return words.join("");
}
function capitalize(word) {
return word.charAt(0).toUpperCase() + word.slice(1);
}
Now you can convert sentences to upper case. It's probably a good idea to remove punctuation marks from the sentence before converting it. Here are a few examples:
alert(toCamelCase("java script")); // javaScript
alert(toCamelCase("json to XML")); // jsonToXML
alert(toCamelCase("ECMA script")); // ECMAScript
The last one appears to be PascalCase but is still considered valid camelCase. You can see the demo here: http://jsfiddle.net/GhKmf/
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.