How can I process each letter of text using Javascript?

Viewed 782565

I would like to alert each letter of a string, but I am unsure how to do this.

So, if I have:

var str = 'This is my string';

I would like to be able to separately alert T, h, i, s, etc. This is just the beginning of an idea that I am working on, but I need to know how to process each letter separately.

I was thinking I might need to use the split function after testing what the length of the string is.

How can I do this?

24 Answers

If the order of alerts matters, use this:

for (var i = 0; i < str.length; i++) {
  alert(str.charAt(i));
}

Or this: (see also this answer)

 for (var i = 0; i < str.length; i++) {
   alert(str[i]);
 }

If the order of alerts doesn't matter, use this:

var i = str.length;
while (i--) {
  alert(str.charAt(i));
}

Or this: (see also this answer)

 var i = str.length;
while (i--) {
  alert(str[i]);
}

var str = 'This is my string';

function matters() {
  for (var i = 0; i < str.length; i++) {
    alert(str.charAt(i));
  }
}

function dontmatter() {
  var i = str.length;
  while (i--) {
    alert(str.charAt(i));
  }
}
<p>If the order of alerts matters, use <a href="#" onclick="matters()">this</a>.</p>

<p>If the order of alerts doesn't matter, use <a href="#" onclick="dontmatter()">this</a>.</p>

One possible solution in pure javascript:

for (var x = 0; x < str.length; x++)
{
    var c = str.charAt(x);
    alert(c);
}

You can try this

var arrValues = 'This is my string'.split('');
// Loop over each value in the array.
$.each(arrValues, function (intIndex, objValue) {
    alert(objValue);
})

New JS allows this:

const str = 'This is my string';
Array.from(str).forEach(alert);

short answer: Array.from(string) will give you what you probably want and then you can iterate on it or whatever since it's just an array.

ok let's try it with this string: abc|⚫️\n⚪️|‍‍‍.

codepoints are:

97
98
99
124
9899, 65039
10
9898, 65039
124
128104, 8205, 128105, 8205, 128103, 8205, 128103

so some characters have one codepoint (byte) and some have two or more, and a newline added for extra testing.

so after testing there are two ways:

  • byte per byte (codepoint per codepoint)
  • character groups (but not the whole family emoji)

string = "abc|⚫️\n⚪️|‍‍‍"

console.log({ 'string': string }) // abc|⚫️\n⚪️|‍‍‍
console.log({ 'string.length': string.length }) // 21

for (let i = 0; i < string.length; i += 1) {
  console.log({ 'string[i]': string[i] }) // byte per byte
  console.log({ 'string.charAt(i)': string.charAt(i) }) // byte per byte
}

for (let char of string) {
  console.log({ 'for char of string': char }) // character groups
}

for (let char in string) {
  console.log({ 'for char in string': char }) // index of byte per byte
}

string.replace(/./g, (char) => {
  console.log({ 'string.replace(/./g, ...)': char }) // byte per byte
});

string.replace(/[\S\s]/g, (char) => {
  console.log({ 'string.replace(/[\S\s]/g, ...)': char }) // byte per byte
});

[...string].forEach((char) => {
  console.log({ "[...string].forEach": char }) // character groups
})

string.split('').forEach((char) => {
  console.log({ "string.split('').forEach": char }) // byte per byte
})

Array.from(string).forEach((char) => {
  console.log({ "Array.from(string).forEach": char }) // character groups
})

Array.prototype.map.call(string, (char) => {
  console.log({ "Array.prototype.map.call(string, ...)": char }) // byte per byte
})

var regexp = /(?:[\0-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/g

string.replace(regexp, (char) => {
  console.log({ 'str.replace(regexp, ...)': char }) // character groups
});

You can now iterate over individual Unicode code points contained in a String by using String.prototype[@@iterator], which returns a value of well known Symbol type Symbol.iterator - the default iterator for array-like Objects (String in this case).

Example code:

const str = 'The quick red  jumped over the lazy ! 太棒了!';

let iterator = str[Symbol.iterator]();
let theChar = iterator.next();

while(!theChar.done) {
  console.log(theChar.value);
  theChar = iterator.next();
}

// logs every unicode character as expected into the console.

This works with Unicode characters such as emoji or non-roman characters that would trip up legacy constructs.

Reference: MDN Link to String.prototype@@iterator.

You can simply iterate it as in an array:

for(var i in txt){
    console.log(txt[i]);
}

In ES6 / ES2015, you can iterate over an string with iterators,as you can see in

Symbol.iterator MDN

var str = 'Hello';
var it = str[Symbol.iterator]();

for (let v of it) {
  console.log(v)
 }
 
//  "H"
//  "e"
//  "l"
//  "l"
//  "o"

It is a declarative style. What is the advantage? You do not have to concern about how to access each element of the string.

You can get an array of the individual characters like so

var test = "test string",
    characters = test.split('');

and then loop using regular Javascript, or else you can iterate over the string's characters using jQuery by

var test = "test string";

$(test.split('')).each(function (index,character) {
    alert(character);
});

you can convert this string into an array of chars using split(), then iterate through it.

const str = "javascript";
const strArray = str.split('');

strArray.map(s => console.log(s));

// There are multiple ways but I find this easiest.

let str = 'This is my string';
for(let character of str) 
  console.log(character)

In today's JavaScript you can

Array.prototype.map.call('This is my string', (c) => c+c)

Obviously, c+c represents whatever you want to do with c.

This returns

["TT", "hh", "ii", "ss", " ", "ii", "ss", " ", "mm", "yy", " ", "ss", "tt", "rr", "ii", "nn", "gg"]

This should work in older browsers and with UTF-16 characters like .

This should be the most compatible solution. However, it is less performant than a for loop would be.

I generated the regular expression using regexpu

var str = 'My String  ';
var regEx = /(?:[\0-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/g


str.replace(regEx, function (char) {
    console.log(char)
});

Hope this helps!

You can access single characters with str.charAt(index) or str[index]. But the latter way is not part of ECMAScript so you better go with the former one.

Related