In: Computer Science
Write a function named "replacement" that takes a string as a parameter and returns an identical string except with every instance of the character "w" replaced with the character "v"
My code:
function replacement(word){
var str=word;
var n=str.replace("w","v");
return n;
}
Syntax Error: function replacement incorrect on input
Not sure how to fix? Can't use a loop for answer
Dear Student ,
As per the requirement submitted above , kindly find the below solution.
Here a new web page with name "replacement.html" is created, which contains following code.
replacement.html :
<!DOCTYPE html>
<html lang="en">
<head>
<!-- title for web page -->
<title>Replace function in javascript</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<script>
//javascript function to replace each w with v
function replacement(word) {
//converting to array
var str = Array.from(word);
var n = "";//variable to store new string
//for loop is used to loop through each element from array
for (var i = 0; i < str.length; i++) {
//checking every character
if (str[i].toLowerCase() == "w") {
//if w found then replace that character
n += str[i].replace("w", "v");
}
else { //if w not then keep as it is
n += str[i];
}
}
return n;//return variable n
}
//function call
console.log(replacement("wowldv"));
</script>
</body>
</html>
======================================================
Output : Open web page replacement.html in the browser and will get the screen as shown below
Screen 1 :replacement.html
NOTE : PLEASE FEEL FREE TO PROVIDE FEEDBACK ABOUT THE SOLUTION.