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.
}
}
Related
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'));
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
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;
}
Can anyone shed light on how to frame a javascript function with two parameters: string and character, and only by using the slice method, return the number of times "a" appears in "lava"?
without slice method
var fruits= "lavaaagg";
var count=0;
for(var i=0;i<fruits.length;i++){
if(fruits[i]!='a')
count++;
}
console.log(fruits.length-count);
I'm not sure why you need the slice method. The slice method isn't for searching substrings (or characters in your case), it extracts a substring.
This should work fine:
function howManyCharInStr(str, char) {
return str.split(char).length - 1;
}
Step-by-step explanation:
str.split(char)
Creates an array of str substrings, using char as a separator. For example:
'fooXbazXbar'.split('X')
// Evaluates to ['foo', 'baz', 'bar']
'lorem ipsum dolor'.split('m')
// Evaluates to ['lore', ' ipsu', ' dolor']
Notice how the array returned has a length of n+1 where n is the number of separators there were. So use
str.split(char).length - 1;
to get the desired result.
For getting number of charecters count
<script type="text/javascript">
function FindResults() {
var firstvariable= document.getElementById('v1');
var secondvariable = document.getElementById('v2');
var rslt = GetCharecterCount(firstvariable, secondvariable );
}
function GetCharecterCount(var yourstring,var charecter){
var matchesCount = yourstring.split(charecter).length - 1;
}
</script>
using slice method
var arr = yourstring.split(charecter);
for( var i = 0, len = arr.length; i < len; i++ ) {
var idx = yourstring.indexOf( arr[i] );
arr[i] = pos = (pos + idx);
str = str.slice(idx);
}
var x= arr.length-1;
example http://jsfiddle.net/rWJ5x/2/
Using slice method
function logic(str,char){
var count = 0;
for(var i = 0; i < str.length; i++){
if(str.slice(i,i+1) == char){
count++;
}
}
return count;
};
console.log( "count : " + logic("lava","a") );
repeat last character of sting n number of times..
function modifyLast(str, n) {
var newstr = str.slice(-1)
var newlaststr = newstr.repeat(n-1)
var concatstring = str.concat(newlaststr);
return concatstring;
}
//modifyLast();
console.log(modifyLast("Hellodsdsds", 3))
how to extract numbers from string using Javascript?
Test cases below:
string s = 1AA11111
string s1= 2111CA2
string s result = 111111
string s1 result = 211112
My code below is not working:
var j = 0;
var startPlateNums = "";
while (j <= iStartLength && !isNaN(iStartNumber.substring(j, j + 1))){
startPlateNums = startPlateNums + iStartNumber.substring(j, j + 1);
j++;
}
How about a simple regexp
s.replace(/[^\d]/g, '')
or as stated in the comments
s.replace(/\D/g, '')
http://jsfiddle.net/2mguE/
You could do:
EDITED:
var num = "123asas2342a".match(/[\d]+/g)
console.log(num);
// THIS SHOULD PRINT ["123","2342"]
A regex replace would probably the easiest and best way to do it:
'2111CA2'.replace(/\D/g, '');
However here's another alternative without using regular expressions:
var s = [].filter.call('2111CA2', function (char) {
return !isNaN(+char);
}).join('');
Or with a simple for loop:
var input = '2111CA2',
i = 0,
len = input.length,
nums = [],
num;
for (; i < len; i++) {
num = +input[i];
!isNaN(num) && nums.push(num);
}
console.log(nums.join(''));