Bracket notation now works on all major browsers, except for IE7 and below.
// Bracket Notation
"Test String1"[6]
// charAt Implementation
"Test String1".charAt(6)
It used to be a bad idea to use brackets, for these reasons (Source):
Answer from Brian Webster on Stack OverflowThis notation does not work in IE7. The first code snippet will return undefined in IE7. If you happen to use the bracket notation for strings all over your code and you want to migrate to
.charAt(pos), this is a real pain: Brackets are used all over your code and there's no easy way to detect if that's for a string or an array/object.You can't set the character using this notation. As there is no warning of any kind, this is really confusing and frustrating. If you were using the
.charAt(pos)function, you would not have been tempted to do it.
Videos
Bracket notation now works on all major browsers, except for IE7 and below.
// Bracket Notation
"Test String1"[6]
// charAt Implementation
"Test String1".charAt(6)
It used to be a bad idea to use brackets, for these reasons (Source):
This notation does not work in IE7. The first code snippet will return undefined in IE7. If you happen to use the bracket notation for strings all over your code and you want to migrate to
.charAt(pos), this is a real pain: Brackets are used all over your code and there's no easy way to detect if that's for a string or an array/object.You can't set the character using this notation. As there is no warning of any kind, this is really confusing and frustrating. If you were using the
.charAt(pos)function, you would not have been tempted to do it.
From MDN:
There are two ways to access an individual character in a string. The first is the
charAtmethod, part of ECMAScript 3:return 'cat'.charAt(1); // returns "a"The other way is to treat the string as an array-like object, where each individual characters correspond to a numerical index. This has been supported by most browsers since their first version, except for IE. It was standardised in ECMAScript 5:
return 'cat'[1]; // returns "a"The second way requires ECMAScript 5 support (and not supported in some older browsers).
In both cases, attempting to change an individual character won't work, as strings are immutable, i.e., their properties are neither neither "writable" nor "configurable".
str.charAt(i)is better from a compatibility perspective if IE6/IE7 compatibility is required.str[i]is more modern and works in IE8+ and all other browsers (all Edge/Firefox/Chrome, Safari 2+, all iOS/Android).
A simple loop works well:
var str = "scissors";
var indices = [];
for(var i=0; i<str.length;i++) {
if (str[i] === "s") indices.push(i);
}
Now, you indicate that you want 1,4,5,8. This will give you 0, 3, 4, 7 since indexes are zero-based. So you could add one:
if (str[i] === "s") indices.push(i+1);
and now it will give you your expected result.
A fiddle can be see here.
I don't think looping through the whole is terribly efficient
As far as performance goes, I don't think this is something that you need to be gravely worried about until you start hitting problems.
Here is a jsPerf test comparing various answers. In Safari 5.1, the IndexOf performs the best. In Chrome 19, the for loop is the fastest.

Using the native String.prototype.indexOf method to most efficiently find each offset.
function locations(substring,string){
var a=[],i=-1;
while((i=string.indexOf(substring,i+1)) >= 0) a.push(i);
return a;
}
console.log(locations("s","scissors"));
//-> [0, 3, 4, 7]
This is a micro-optimization, however. For a simple and terse loop that will be fast enough:
// Produces the indices in reverse order; throw on a .reverse() if you want
for (var a=[],i=str.length;i--;) if (str[i]=="s") a.push(i);
In fact, a native loop is faster on chrome that using indexOf!

Javascript arrays cannot have "string indexes". A Javascript Array is exclusively numerically indexed. When you set a "string index", you're setting a property of the object. These are equivalent:
array.a = 'foo';
array['a'] = 'foo';
Those properties are not part of the "data storage" of the array.
If you want "associative arrays", you need to use an object:
var obj = {};
obj['a'] = 'foo';
Maybe the simplest visualization is using the literal notation instead of new Array:
// numerically indexed Array
var array = ['foo', 'bar', 'baz'];
// associative Object
var dict = { foo : 42, bar : 'baz' };
Because the length is defined to be one plus the largest numeric index in the array.
var xs = [];
xs[10] = 17;
console.log( xs.length ); //11
For this reason, you should only use arrays for storing things indexed by numbers, using plain objects instead if you want to use strings as keys. Also, as a sidenote, it is a better practice to use literals like [] or {} instead of new Array and new Object.
Is this close to what you're looking for?
function findCharIndex(str,char){
for (let index = 0; index < str.length; index++) {
if (str[index] === char) {
return index;
}
}
return -1;
}
Iterate through each element in str and check if it's the character you want:
let string = "This is a string";
let char = "a";
let index;
for (let i = 0; i < string.length; i++) {
if (string[i] == char) {
index = i;
break;
}
}
console.log(index);