Uncaught ReferenceError: Invalid left-hand side in assignment. Javascript - javascript

I want to replace a character in a string (original) with another string.
I am getting an error on running the debugger.
I dont understand what is wrong with the syntax.
<!DOCTYPE>
<html>
<head>
<title>HI there</title>
<meta lang="english">
</head>
<body>
<div>
Enter the original string<input id="original" value="" type="text"> <br>
Enter the replacing string<input id="replacing" value="" type="text"><br>
Enter the location to be replaced<input id="tobereplaced" value="" type="text"><br>
</div>
<br>
<button type="submit" onclick="replace()">Submit</button>
<br> Here you go the replaced string is:
<script>
function replace() {
var original = document.getElementById("original").value;
var replacing = document.getElementById("replacing").value;
var tobereplaced = document.getElementById("tobereplaced").value;
var replaced = "";
var originalLength = original.length;
var tobereplacedLength = tobereplaced.length;
var k = 0;
for (var i = 0; i < originalLength; i++) {
replaced.charAt(k) = original.charAt(i)
if (original.charAt(i) == replacing.charAt(0)) {
replaced = replaced + tobereplaced;
k = k + tobereplacedLength;
i++;
}
k++;
}
document.getElementById("replaced").innerHTML = replaced;
}
</script>
<h1 id="replaced"></h1>
</body>
</html>

you are trying to change the character of an empty string at line no:28 [replaced.charAt(k) = original.charAt(i)] this is the issue.
Also there are some unwanted increment in the code. please find the corrected below
I have updated the code below with // comment the code and added correct code. its working
// var k = 0; //Commented
// debugger; //Commented
for (var i = 0; i < originalLength; i++) {
if (original.charAt(i) == replacing.charAt(0)) {
replaced = replaced + tobereplaced;
// k = k + tobereplacedLength; //Commented
// i++; //Commented
} else{
replaced = replaced + original.charAt(i);
}
// k++; //Commented
}

Here is a more simplistic approach to the problem. It takes advantage of the .split() & .join() functions rather than using a for loop.
function replace() {
// set original string
var original = document.getElementById("original").value, // << use commas so you don't have to keep typing var
// set replacing string
replacing = document.getElementById("replacing").value,
// initialize newval
newValue,
// set replace position - this could also be called index
replacePosition = document.getElementById("tobereplaced").value; // << end variable declarations with semicolon
// split original string into array of characters
var splitOriginal = original.split("");
// use replacePosition as index value of character to replace
// & replace that character with replacing value
splitOriginal[replacePosition] = replacing;
// join array to form new string value
newValue = splitOriginal.join("");
document.getElementById("replaced").innerHTML = newValue;
}
<html>
<head>
<title>HI there</title>
<meta lang="english">
</head>
<body>
<div>
Enter the original string
<input id="original" value="" type="text">
<br>Enter the replacing string
<input id="replacing" value="" type="text">
<br>Enter the location to be replaced
<input id="tobereplaced" value="" type="text">
<br>
</div>
<br>
<button type="submit" onclick="replace()">Submit</button>
<br>Here you go the replaced string is:
<h1 id="replaced"></h1>
</body>
</html>

Related

How to loop in JavaScript

DISCLAIMER: i'm legit a newbie
I have a 2nd parameter in the getInput function, I should use it for the 9 zeros that I should input. But I don't know how to loop it to become 9 zeros instead of putting it in a variable.
How do I loop and store 9 zero's into my "digit" parameter without declaring it as var zr = "000000000"
here's my code:
<html>
<head>
<title>Search</title>
<script>
//This method does the processing
function getInput(input, digit){
var str=input.substring(0,input.length);
var padd0=9-str.length;
var zr="000000000";
var zrsub=zr.substring(0,padd0);
var output="A"+zrsub+""+str;
//can also be var output=input[0]+zrsub+""+str;
return output;
}
//Displays output
function showOutput(){
var input=document.getElementById("search-input").value;
var dislay=document.getElementById("search-output");
dislay.value=getInput(input);
}
</script>
</head>
<body>
<div class="wrapper">
<input type="text" id="search-input">
<input type="button" id="btn" value="ENTER" onclick="showOutput()"> <br><br>
<input type="text" id="search-output">
</div>
</body>
</html>
Sorry just a newbie in this whole programming thing. Just a little confused.
with for loop join string
function joinString(input,digit) {
var inputArr = input.split("");
// var n = 9; // the length of the ouput string;
for (var i = 0; i < digit; i++) {
inputArr.unshift(0);
if (inputArr.length === digit) {
return inputArr.join("");
}
}
}
console.log(joinString("123456"));
You can use padStart
function getInput(input, digit){
return 'A'+ input.toString().padStart(digit, '0');
}
document.getElementById('target').innerHTML = getInput(132,9)
<p id="target"></p>
IE may not support it though.

Call Script Javascript and HTML

I need some help because my callback function, parseMovie() is only being called once! Despite being in a for loop which iterates it twice. I am using a free Rottentomatoes API
The output only returns one ID, and not two ID's!
And runs parseMovie() only once and returns the movie ID with the last movie.
Does anyone have a fix for this script running problem?
HTML CODE
<!doctype html>
<html class="no-js">
<head>
<title>Movies</title>
<link rel="stylesheet" href="css/main.css">
<script src="js/main.js"></script>
</head>
<body>
<form name="input">
<p> Actor/Actress Name: <input type="text" name="fullName"> </p>
<p> Movie 1 <input type="text" name="movie"> </p>
<p> Movie 2 <input type="text" name="movie"> </p>
<p><input type="button" value="Search movies" onclick="getMovies()"></p>
<p><textarea name="output" readonly> </textarea> </p>
</form>
</body>
</html>
JAVASCRIPT
//api key
var APIKEY = "qf54ubt95fea9n7jytr5xh6h";
var movieID = new Array();
var actor = new Array();
var actorName = "Jennifer Lawrence";
var movieTitle;
var output;
function callScript(call) {
var script = document.createElement('script');
script.setAttribute("src", call);
document.body.appendChild(script);
}
function getMovies() {
for (var x=0; x<2; x++) {
movieTitle = document.getElementsByName('movie')[x].value;
movieTitle= cleanMovieTitle(movieTitle);
var movieURL = "http://api.rottentomatoes.com/api/public/v1.0/movies.json?q=";
callScript(movieURL + movieTitle + "&page_limit=10&page=1&apikey=" + APIKEY + "&callback=parseMovie");
}
}
function cleanMovieTitle(movie) {
movie = movie.trim();
movie = movie.replace(/ /g, "+");
return movie;
}
function parseMovie(data) {
var titleData = data.movies;
for (var t=0; t<titleData.length; t++) {
movieID[movieID.length] = titleData[t].id;
aCast = titleData[t].abridged_cast;
sample = [];
for (var person = 0; person < aCast.length; person++) {
sample[sample.length] = aCast[person].name;
}
actor[actor.length] = sample;
}
for (var arry = 0; arry < actor.length; arry++) {
if (actor[arry].indexOf(actorName) >= 0) {
output = movieID[arry];
break;
} else {
alert("spelling error of some sort! Error 404");
}
}
document.input.output.value = output;
}
Your statement var titleData = data.movies; is wrong, because the data returned by the API contains an array of movies.
You have to iterate through data.movies to get the data for the other movies (and not only the first one).
See the raw JS code and JSON data returned by the API: api.rottentomatoes.com
Three things that strike me as odd that might be causing the problem.
Using for…in for an array is considered bad practice, especially when there's a native forEach method and a polyfill for ie8-
cleanMovieTitle isn't doing anything because it doesn't return a value. If you were passing it an array or object, it would pass by reference and it would be altered, but that is considered bad practice for the exact reason that it's not working. You're passing a value, the function modifies that value within the function's scope, then does nothing with it. You need to return the string and set movieTitle = cleanMovieTitle(movieTitle); So maybe the API isn't returning for one of the titles because it hasn't been cleaned. See Passing by Reference or by Value.
The callback may be is getting called again before it finishes running. Not sure on this one, but you could check by flooding the loop with console.logs and seeing whether it's the case.
Edit
So I just ran your script on this page and I'm getting an error on document.input.output.value = output; As expected, parseMovies runs twice when I remove this line. What's document.input?

Stripping whitespaces in string before adding to select box [duplicate]

This question already has answers here:
Trim string in JavaScript
(20 answers)
Closed 9 years ago.
I need your help,
I can't seem to be able to strip away the whitespaces in my data string before adding them to my select box.
(BTW the spaces in between the data string are deliberate as I am working with an old dataset and slowly converting it to a non-space string)
How do you accomplish this? I thought that I had the logic all right:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function parseData() {
var data = "1234567, 8910111, 9632587,6541237,9631478, 1010232"
var options = data.split(",");
var select = document.getElementById('list')
select.innerHTML = ""
for(var i=0; i<options.length; i++)
select.options[i] = new Option(options[i], i);
}
</script>
</head>
<body>
<input type="button" value="load list" onclick="parseData()"/>
<br>
<select id="list"></select>
</body>
</html>
You can trim whitespaces when filling the selector:
options[i].replace(/^\s+|\s+$/g, '')
The jsfiddle is here.
No Regex required, use Options[i].trim() (trim removes any whitespace (including line breaks, tab stops and whatevs) on both sites of the string)
for(var i=0; i<options.length; i++)
select.options[i] = new Option(options[i].trim(), i);
Try this:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function parseData() {
var data = "1234567, 8910111, 9632587,6541237,9631478, 1010232"
var options = data.split(",");
var select = document.getElementById('list')
select.innerHTML = ""
for(var i=0; i<options.length; i++)
select.options[i] = new Option(options[i].replace(" ", ""), i); // cross browser
// or this one
//select.options[i] = new Option(options[i].trim(), i); // ie9+ and all other browsers
}
</script>
</head>
<body>
<input type="button" value="load list" onclick="parseData()"/>
<br>
<select id="list"></select>
</body>
</html>

Javascript change text of all inputs

I'm really newbie at Web Development and I'm trying to change the text of some inputs, with Javascript. Here is a example of what my code have to do
<!DOCTYPE html>
<html>
<body>
<p>Click the button to replace "R$" with "" in the field below:</p>
<input id="demo" value="R$ 1223,43"></input>
<input id="demo1" value="R$ 134523,67"></input>
<input id="demo2" value="R$ 12453,41"></input>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
var x=document.getElementByTagName("input")
for(var i = 0; i < x.length; i++) {
var str=x[i].innerHTML;
var n=str.replace(",",".");
var n1 = n.replace("R$ ","");
document.getElementById("demo").innerHTML=n1;
}
}
</script>
</body>
</html>
So, I want to withdraw the "R$" and replace "," to "." for some math operations. And I have to do this with all inputs in my code.
You were nearly there, replacing a few things to make it look similar to this:
function myFunction() {
var x = document.getElementsByTagName("input"); // ; was missing and you used getElementByTagName instead of getElementsByTagName
for (var i = 0; i < x.length; i++) {
var str = x[i].value; // use .value
var n = str.replace(",", ".");
var n1 = n.replace("R$ ", "");
//document.getElementById("demo").innerHTML=n1; // use x[i] again instead
x[i].value = n1; // and again use .value
}
}
DEMO - Running updated code
These are the needed steps - at least step 1 through 3
moved the script to the head where it belongs
changed getElementByTagName to getElementsByTagName, plural
get and change x[i].value
chained the replace
DEMO
<!DOCTYPE html>
<html>
<head>
<title>Replace example</title>
<script>
function myFunction() {
var x=document.getElementsByTagName("input"); // plural
for(var i = 0; i < x.length; i++) {
var str=x[i].value;
x[i].value=str.replace(",",".").replace("R$ ","");
}
}
</script>
</head>
<body>
<p>Click the button to replace "R$" with "" in the field below:</p>
<input id="demo" value="R$ 1223,43"></input>
<input id="demo1" value="R$ 134523,67"></input>
<input id="demo2" value="R$ 12453,41"></input>
<button onclick="myFunction()">Try it</button>
</body>
</html>
First of all, use .value instead of .innerHTML. .innerHTML referes to text within the opening and closing of the tag.
Secondly, correct the spellings at var x=document.getElementByTagName("input")
it should be getElementsByTagName
this function should do what you want:
function myFunction()
{
var eles=document.getElementsByTagName("input");
for(var i = 0; i < eles.length; i++)
{
if(eles[i].type != 'text') continue; // inputs that aren't of type text dont make sense here
var str = eles[i].value;
str=str.replace(",",".");
str=str.replace("R$ ","");
eles[i].value=str;
}
}

Camelcase using split( ) twice in Javascript

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/

Categories

Resources