Reputation: 19337
ok I want do have a jscript below
$(document).ready(function(){
var str = 'post'; //the subject string
var arr =[0,2]; //to uppercase character index 0 and 2
str = str.split("");
for(var i = 0; i < str.length; i++){
if($.inArray(i,arr)){
str[i] = str[i].toUpperCase();
}
}
str = str.join('');
alert(str);
//the result must be PoSt
});
and you may see it running here
http://jsfiddle.net/laupkram/WfUUp/
now what I want there is to provide a subject string and an array.
the subject string is the string to be process and the array contains numerical values that will represent the character index in the string to uppercase.
did i miss something with my script that's why I get undersirable results?
Upvotes: 3
Views: 6300
Reputation: 1869
I would re-write this as
var str = 'post'; //the subject string
var arr =[0,2]; //to uppercase character index 0 and 2
str = str.split("");
for(i = 0; i < arr.length; i++){
str[arr[i]]=str[arr[i]].toUpperCase();
}
str = str.join('');
alert(str);
Upvotes: 1
Reputation: 13709
2 Things that I see wrong here:
No need to split
the str, you can loop over it normally.
You got inArray()
wrongly. The below snippet from jquery api for inArray
The $.inArray() method is similar to JavaScript's native .indexOf() method in that it returns -1 when > it doesn't find a match. If the first element within the array matches value, $.inArray() returns 0.
So, as inArray
is returning -1 for indexes that it didn't find, you if
statement is becoming true, and hence you are getting the result as 'PoST'.
Upvotes: 1
Reputation: 19465
Check the docs for $.inArray . It returns the index of the element that was found or -1
if not found.
$(document).ready(function(){
var str = 'post'; //the subject string
var arr =[0,2]; //to uppercase character index 0 and 2
str = str.split("");
for(var i = 0; i < str.length; i++){
//CHANGE HERE
if($.inArray(i,arr) != -1){
//^^ change this
str[i] = str[i].toUpperCase();
}
}
str = str.join('');
alert(str);
//the result must be PoSt
});
Upvotes: 3
Reputation: 25145
$(document).ready(function() {
var str = 'post'; //the subject string
var arr = [0, 2]; //to uppercase character index 0 and 2
str = str.split("");
for (var i = 0; i < arr.length; i++) {
if (str[arr[i]]) {
str[arr[i]] = str[arr[i]].toUpperCase();
}
}
str = str.join('');
alert(str);
//the result must be PoSt
});
Upvotes: 3