passing a string to javascript function and convert it - javascript

var str1 = document.getElementById('string').value;
var str = str1.toUpperCase();
function correctstring() {
for (var i=0;i < str.length ; i++) {
if(str[i]==='H'){str[i]='R';}
else if(str[i]==='V'){str[i]='L';}
else if (str[i] === 'G'){ str[i]='F'; }
else {atert('the string has a wrong input, Please enter the right chars for english(R,L,F) for swedish (H,V,G)');
}
}
}
correctstring();

String isn't considered array in JS, just cast it as array and then cast i back:
st = str1.split("");
//Your code
str1 = st.join("")
Don't forget to change str1 to st in your loop

Related

How to pick only Capital characters from the string?

I am try to pick capital characters from the string with the help of a function and for loop but i can't figure out how i can do it i try using toUpperCase as you see it in the code but it is not work any idea how i can do it ?
function onlyCapitalLetters(cap){
var string = "";
for(var i = 0; i < cap.length; i++){
if(cap[i] === cap.toUpperCase()){
string += cap[i];
}
}
return string;
}
onlyCapitalLetters("Apple");
You can try the regex, with String.prototype.match to return capital letters only:
function onlyCapitalLetters(cap){
return cap.match(/[A-Z]/g, "").join(''); // join the array to return a string
}
console.log(onlyCapitalLetters("Apple"));
console.log(onlyCapitalLetters("BUTTerfly"));
console.log(onlyCapitalLetters("LION"));
Can you try like this
function findUpcase(value){
input = value
data = ""
input.split("").map(res => {
if(res == res.toUpperCase()){
data = data+ res
}
})
return data
}
console.log( findUpcase("MyNameIsVelu") );
//'MNIV'
As noted in comments you need to change cap.toUpperCase() to cap[i].toUpperCase().
But you can do it with just one replace:
console.log('Apple Orange'.replace(/[^A-Z]/g, ""));
It is possible to use replace method with Regex to eliminate numbers and letters written in lowercase:
let str = 'T1eeeEeeeSssssssTttttt';
let upperCase = str.replace(/[a-z0-1]/g, '')
console.log(upperCase);
Please Use Below code to get Capital letter of the sentence :
Demo Code
var str = 'i am a Web developer Student';
var sL = str.length;
var i = 0;
for (; i < sL; i++) {
if (str.charAt(i) != " ") {
if (str.charAt(i) === str.charAt(i).toUpperCase()){
console.log(str.charAt(i));
break;
}
}
}

What is wrong with the logic of my character changing function?

I've tried to create a character changing function for strings, it suppose to change all the "-" to "_", and it only does it for the first character and leaves the rest. If someone could explain it would be grate.
function kebabToSnake(str) {
var idNum = str.length;
for(var i = 0; i <= idNum; i++) {
var nStr = str.replace("-", "_");
}
return nStr;
}
var nStr = str.replace("-", "_");
So, on each iteration, you're replacing the first found - character in the original string, not the string that you've already replaced characters from already. You can either call .replace on just one variable that you reassign:
function kebabToSnake(str) {
var idNum = str.length;
for(var i = 0; i < idNum; i++) {
str = str.replace("-", "_");
}
return str;
}
console.log(kebabToSnake('ab-cd-ef'));
(note that you should iterate from 0 to str.length - 1, not from 0 to str.length)
Or, much, much more elegantly, use a global regular expression:
function kebabToSnake(str) {
return str.replace(/-/g, '_');
}
console.log(kebabToSnake('ab-cd-ef'));

“str.fromCharCode is not a function”

Im getting the following errors:
str.fromCharCode is not a function
newStr.push is not a function
I have no clue why I’m getting those errors tbh. I might be using methods the wrong way
function rot13(str) {
var newStr = str;
for (i = 0; i < str.length; i++) {
str.fromCharCode(str[i] - 13);
newStr.push(i);
}
return newStr;
}
// Change the inputs below to test
console.log(
rot13("SERR PBQR PNZC")
)
You could try something like:
function rot13(str) {
var newStr = [];
for(i = 0; i < str.length; i++){
let x = String.fromCharCode(str[i].charCodeAt()-13);
newStr.push(x);
}
return newStr.join("");
}
It is String.fromCharCode, not myString.fromCharCode
Lastly you want charCodeAt to subtract from
Also you cannot push a char to a string. push is an Array method
function rot13(str) {
var newStr = []; // using an array - you can use += to concatenate to string
for (i = 0; i < str.length; i++) {
// I suggest you do not convert the space.
// Here I converted it to another type of space but you can use " " if you want
var x = str[i] == " " ? "\u2005":String.fromCharCode(str[i].charCodeAt(0) - 13);
newStr.push(x);
}
return newStr.join("");
}
// Change the inputs below to test
console.log(
rot13("SERR PBQR PNZC")
)

Reverse string to find palindromes in JavaScript

I have two strings. The first is normal string, the second I want to be a reversed string like first one, but in the console I didn't get the look of like first one listed by commas. How can I fix that ?
Normal string -
Revered string -
window.onload = function(){
inputBox = document.getElementById("myText");
btn = document.getElementById('sub');
btn.addEventListener("click",function(event){
event.preventDefault();
findPalindromes(inputBox.value);
});
str = inputBox.value;
function findPalindromes(str) {
var words = str.split(" ");
for (var i = 0; i < words.length - 1; i++) {
words[i] += " ";
}
console.log(words);
var newString = "";
for (var i = words.length - 1; i >= 0; i--) {
newString += words[i];
}
console.log(newString);
}
}
If you really just want to find out if a string is a palindrome, you can do something as simple as this:
function isPalindrome(str) {
return str.toLowerCase() === str.toLowerCase().split('').reverse().join('');
}
The first for loop is not necessary. You do not need to concatenate a space character " " to the element of the array, where the variable assignment i
var i = 0;
and condition
i < words.length - 1;
stops before reaching last element of array.
var newString = "";
for (var i = words.length - 1; i >= 0; i--) {
newString += words[i] + " ";
}
console.log(newString);
In your "normal" string example, you're printing words to the console. Let's first look at what words is: var words = str.split(" ");
The String.split() function returns an array of strings. So your "normal" string is actually an array of strings (The brackets [] and comma separated strings in the console output indicate this).
In the second example, you're logging newString. Let's look at where it comes from: var newString = "";
newString is a String. If you want it to be an array of strings like words, you would declare it with var newString = [];. Arrays do not support += so newString += words[i]; would become newString.push(words[i]);
The above explains how to get newString to behave like words, the code you've written is not looking for a palindrome word, but rather a palindrome sentence: "Bob is Bob" is not a palindrome (reversed it is "boB si boB") but it could be a Palindrome sentence (if such a thing exists).
Thanks to all, I wrote this solution for the problem. I hope this is the right answer.
window.onload = function(){
inputBox = document.getElementById("myText");
btn = document.getElementById('sub');
btn.addEventListener("click",function(event){
event.preventDefault();
findPalindromes(inputBox.value);
});
str = inputBox.value;
function findPalindromes(str) {
var words = str.split(" "),
newString = [];
for (var i = 0; i < words.length - 1; i++) {
if ((words[i] === words[i].split('').reverse().join('')) === true) {
newString.push(words[i]);
}
}
console.log(newString);
}
}
var words = " ";
function reverse_arr(arr){
var i = arr.length - 1;
while(i >= 0){
words += a[i] + " ";
i--;
}
return words;
}

Make a character capitalize within a strin in javascript not working

I am trying to capitalize a character within a string in javascript, my codes are :
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var str = "string";
for(m = 0; m < str.length; m++){
if(str[m] == "r"){
str[m+1] = str[m+1].toUpperCase();
}
}
alert(str);
}
</script>
So what I am trying to do is, if the character is r,capitalize the next character. But is not woking means its the same string alerting.
Strings in JavaScript are immutable, you need to create a new string and concatenate:
function myFunction() {
var str = "string";
var res = str[0];
for(var m = 1; m < str.length; m++){
if(str[m-1] == "r"){
res += str[m].toUpperCase();
} else {
res += str[m];
}
}
}
But you could simply use regex:
'string'.replace(/r(.)/g, function(x,y){return "r"+y.toUpperCase()});
String are immutable. So You can convert string to array and do the replacements and then convert array to string. Array are mutable in Javascript.
var str = "string".split('');
for(m = 0; m < str.length - 1; m++){
if(str[m] == "r"){
str[m+1] = str[m+1].toUpperCase();
}
}
alert(str.join(''));
Try this
<script>
function myFunction() {
var p='';
var old="r";
var newstr =old.toUpperCase();
var str="string";
while( str.indexOf(old) > -1)
{
str = str.replace(old, newstr);
}
alert(str);
}
</script>
But you it will not work in alart.
Hope it helps
var str = "string";
for(m = 0; m < str.length; m++){ // loop through all the character store in varable str.
if(str[m] == "r") // check if the loop reaches the character r.
{
alert(str[m+1].toUpperCase()); // take the next character after r make it uppercase.
}
}

Categories

Resources