I have an assignment in school but I'm totally stuck.
My assignment:
Make a program that ask for a text and then write out the text several times. First with just one letter, then with two and so on. For example, if the user write "Thomas", your program should write out "T", "Th, "Tho, "Thom", and so on.
My hopeless attempt
I been trying to use "Substring" and a loop to make it work but I'm not sure I'm on the right path or not. Right now my code look like this:
<head>
<meta charset= "UTF-8"/>
<title> assignment14 - Johan </title>
<script type="text/javascript">
var text= test.length;
for (i=0;i< test.length;i++)
function printit()
{
var str = test;
var res = str.substring (i, 2);
document.getElementById("test").innerHTML = res;
}
</script>
</head>
<body>
<h1>Assignment 14</h1>
<form name="f1">
<input type="text" id="test" value="" />
<input type="button" value="Hämta" onclick="printit(document.getElementById('test'))" />
</form>
</body>
Just need some kind of hint If I'm going in the right direction or not, should I use some other functions? Very thankful for help.
You have to rewrite a script.When you want to extract one by one you can use substring(); function.
How to Call : StringObject.substring (StartPoint,endPoint);
Solution:
<script type="text/javascript">
function printit(){
var test=document.getElementById("test").value;
var text= test.length;
for (i=0;i<= text;i++)
{
var res = test.substring (i, 0);
document.write(res);
document.write("<br/>");
}
}
</script>
You are on the right way. substring(start,end) in javascript gives you the consecutive part of the string letters from start index to end. You just use it in a wrong way for your case. You have to call it like this:
substring(0,i)
You need to make few changes to your code:
1) use document.getElementById('test').value in printit function call at onclick as you have to send the value of the textbox instead of innerHTML.
2) Modify the printif function-
function printit(test)
{
document.getElementById('test').value=''; /*remove existing text from textbox*/
for (i=0;i< test.length;i++) {
var res = str.substring (0, i+1);
document.getElementById("test").value += ' '+res;
}
}
In printit function empty the text box and then append each substring to the existing text to get "T Th Tho Thom.." and so on
Hope this helps.
I don't use for-loop for this (whenever possible, I prefer functional style). Instead, I write a function that returns an array of substrings:
const substrings = string =>
Array.from(string).map((_, i) => string.slice(0, i + 1))
And here's a working codepen
Output several time using substring() method can be done as below, create a function which performs this task of extracting the user inputted string on button click using forloop and substring() method.
var intp = document.querySelector("input");
var btn = document.querySelector("button");
var dv = document.querySelector("div");
btn.onclick = function() {
var b = intp.value;
for (var i = 1; i <= b.length; i++) {
var c = b.substring(0, i);
dv.innerHTML += c + "<br/>";
}
}
div{
width:400px;
background:#111;
color:yellow;
}
<input type="text">
<button>Click</button>
<br/><br/>
<div></div>
You have used a correct way for doing this, but as one of user suggest the start and end value of substring() was not correct.
Related
I was working on this code, and I got stuck here as a JS rookie and need help. How would you rewrite this block, using % operator, instead of if statement?
<!DOCTYPE html>
<html>
<head>
<script>
window.onload=function(){
var letters = ["A","B","C"]
var counter = 0;
var timer=setInterval(
function(){
counter= counter+1;
if (counter==letters.length){
counter=0;
}
document.getElementById("demo").value=letters[counter];
},1000)
}
</script>
</head>
<body>
<input type="text" id="demo" value="A">
</body>
</html>
Simple use it after doing your add operation to return the remains after division (or modulus):
const letters = ["A","B","C"]
let counter = 0;
setInterval(function(){
counter = (counter+1) % letters.length;
document.getElementById("demo").value = letters[counter];
}, 1000);
<input type="text" id="demo" value="A" />
Couple of other tips, use const if the values don't change (like your array), and let if it can definitely change. Also, you don't need to store your interval here as you never cancel it, so no need for const timer in that case. Simplifies the code a lot!
I create a website with the possibility of using either English or Arabic language. When the language is Arabic, I need some words to remain English.
For Arabic, I use
direction: rtl;
As an example for the following sentence,
مرحبا: Prabhashi (NEW) أهلا بك
the result by rtl is as follows,
But I need the result to be,
أهلا بك (NEW) Prabhashi :مرحبا
Please help me with this.
Here is a way to solve your problem. It iterates over the string, adds all the words in the strings separated by a " " into an array and then reverses it
function reverse_sentence(str){
str += " ";
var words = [];
var last_break = 0,word_length = 0;
for(var i = 0; i < str.length; i++){
if(str[i] == " "){
var word = str.substr(last_break, word_length);
words.push(word);
last_break = i + 1;
word_length = 0;
}else{
word_length++;
}
}
return words.reverse();
}
alert(reverse_sentence("Hi my name is Albin"));
I think as per the link: https://www.w3.org/TR/WCAG20-TECHS/H34.html
You will have to add this character after your brackets to tell the browser that it should be LTR. Like the example below:
<!DOCTYPE html>
<head>
<meta charset="unicode">
</head>
<body>
<div dir="rtl">
مرحبا: Prabhashi (NEW) أهلا بك
</div>
</body>
</html>
I think this will be the simplest answer for your problem.
I want to append the given string to the textarea i have, i want to append the text in the way it should look like someone typing on the texture,because i have the voice playing in the background for 6 seconds which which says the same thing to be written.
<textarea id='typeable' style='font-size:18px;background:#F8E71C'></textarea>
<script>
function addText(event) {
document.getElementById("typeable").value += "Hello welcome to the new world of javascript"
}
</script>
how can i do this
Count the number of characters in the sentence, and then calculate the time for each char by dividing the total time with the no. of characters and then call the time Interval and run it until all the characters are printed.
Still you can decide the time taken to print each character and modify it as per your need. Please note that the time is taken in milliseconds.
var chars = "Hello welcome to the new world of javascript".split("");
var textarea = document.querySelector('textarea');
var total_time=6000;
var index = 0;
var time_per_char = total_time/chars.length;
var t = setInterval(function(){
textarea.value += chars[index];
index++;
if (index === chars.length){
clearInterval(t);
}
},time_per_char);
<textarea style="width:100%;background:#E1ECF4">
</textarea>
Code is attached below:
<!DOCTYPE html>
<html>
<script>
function appendText() {
document.getElementById("typeable").value= document.getElementById("typeable").value + "Hello welcome to the new world of javascript";
}
</script>
<body onload="appendText()">
<textarea id='typeable' style='font-size:18px;background:#F8E71C'></textarea>
</body>
</html>
This script is supposed to take a list of links, transform some by changing some words and eliminate others containing specific string of characters.
The first part is ok. I need help with the second. The line
x = x.replace(/^.+/category/.+$/mg, "");
doesn't work even if we change the + with *. I used sources from here (1 & 2 ). So, help the noob.
<!DOCTYPE html>
<html>
<body>
<h3>Instert your links</h3>
input:<br>
<textarea id="myTextarea">
http://example.com/ad/123.html
http://example.com/ad/345.html
http://example.com/ad/3567.html
http://example.com/category/fashion.html
http://example.com/ad/8910.html
http://example.com/category/sports.html
</textarea>
<button type="button" onclick="myFunction()">Get clean links</button>
<p id="links"></p>
<script>
function myFunction() {
x = document.getElementById("myTextarea").value;
x = x.replace(/http:\/\/example.com\/ad\//g, "http://example./com/story/");
x = x.replace(/\n/g,"</br>");
x = x.replace(/^.+/category/.+$/mg, "");
document.getElementById("links").innerHTML = x;
}
</script>
</body>
</html>
I think you need to escape your forward slashes as you are also using them as the regex delimiter.
x = x.replace(/^.+\/category\/.+$/mg, "");
Assuming that you want to copy those lines in <p> remove line containing category in it.
change your function to
function myFunction() {
x = document.getElementById("myTextarea").value;
var lines = x.split("\n").filter( function(val){
return val.indexOf( "category" ) == -1;
});
document.getElementById("links").innerHTML = lines.join( "<br>" );
}
I have an array with 8 elements defined within a script.
I'd like to know how I can pass all the values of this array to a single hidden element.
Pls help.
<script ='text/javascript'>
function abc(){
var arr= new Array(8);
for (var i=0; i<8;i++)
{
arr[i]= ...;
}
</script>
<input type="hidden" id="arrs" name="arrs" value= ? >
you can join them with comma ','
$('#arrs').val(arr.join(','));
From the comments on the question itself
I will have to access this input
hidden element in another js later on
using document.forms.element(''). so
thought it would be easier using a
single element.
It would be easiest to not use any form element at all. Not sure why you want to take such a detour. You have a JavaScript variable, you can use that directly in "another script later on":
<script type="text/javascript" id="firstScript">
function abc(){
var arr = [];
for (var i=0; i<8; i++) {
arr.push(...);
}
return arr;
}
var myArray = abc();
</script>
<!-- time passes, but we're still on the same page... -->
<script type="text/javascript" id="anotherScript">
doSomethingWith(myArray);
</script>
You can try like this:
<script>
function a(){
var arr= new Array(8);
for (var i=0; i<8;i++)
{
arr[i]= i;
}
document.getElementById('d').value = arr;
alert(document.getElementById('d').value);
}
</script>
<input id="d" type="hidden" />
<input type="button" onclick="javascript:a();" value="A" />
Hope this helps.
If the values are only strings or integers, you can try joining them with a seperator not present in your input:
document.getElementById("arrs").value = arr.join("###");
And you can do
myArr = document.getElementById("arrs").value.split("###");
To retreive that array back.