admin管理员组文章数量:1125770
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?
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?
Share Improve this question edited Feb 5, 2021 at 19:38 cobrexus 4,7885 gold badges23 silver badges49 bronze badges asked Dec 27, 2009 at 17:29 Nic HubbardNic Hubbard 42.1k66 gold badges253 silver badges415 bronze badges 1 |24 Answers
Reset to default 648If the order of alerts matters, use this:
for (let i = 0; i < str.length; i++) {
alert(str.charAt(i));
}
Or this: (see also this answer)
for (let i = 0; i < str.length; i++) {
alert(str[i]);
}
If the order of alerts doesn't matter, use this:
let i = str.length;
while (i--) {
alert(str.charAt(i));
}
Or this: (see also this answer)
let i = str.length;
while (i--) {
alert(str[i]);
}
var str = 'This is my string';
function matters() {
for (let i = 0; i < str.length; i++) {
alert(str.charAt(i));
}
}
function dontmatter() {
let 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>
It's probably more than solved. Just want to contribute with another simple solution:
var text = 'uololooo';
// With ES6
[...text].forEach(c => console.log(c))
// With the `of` operator
for (const c of text) {
console.log(c)
}
// With ES5
for (var x = 0, c=''; c = text.charAt(x); x++) {
console.log(c);
}
// ES5 without the for loop:
text.split('').forEach(function(c) {
console.log(c);
});
How to process each letter of text (with benchmarks)
https://jsperf.com/str-for-in-of-foreach-map-2
for
Classic and by far the one with the most performance. You should go with this one if you are planning to use it in a performance critical algorithm, or that it requires the maximum compatibility with browser versions.
var str = "Hello";
for (var i = 0; i < str.length; i++) {
console.info(str[i]);
}
for...of
for...of is the new ES6 for iterator. Supported by most modern browsers. It is visually more appealing and is less prone to typing mistakes. If you are going for this one in a production application, you should be probably using a transpiler like Babel.
let result = '';
for (let letter of str) {
result += letter;
}
forEach
Functional approach. Airbnb approved. The biggest downside of doing it this way is the split()
, that creates a new array to store each individual letter of the string.
Why? This enforces our immutable rule. Dealing with pure functions that return values is easier to reason about than side effects.
// ES6 version.
let result = '';
str.split('').forEach(letter => {
result += letter;
});
or
var result = '';
str.split('').forEach(function(letter) {
result += letter;
});
The following are the ones I dislike.
for...in
Unlike for...of, you get the letter index instead of the letter. It performs pretty badly.
var result = '';
for (var letterIndex in str) {
result += str[letterIndex];
}
map
Function approach, which is good. However, map isn't meant to be used for that. It should be used when needing to change the values inside an array, which is not the case.
// ES6 version.
var result = '';
str.split('').map(letter => {
result += letter;
});
or
let result = '';
str.split('').map(function(letter) {
result += letter;
});
One possible solution in pure JavaScript:
for (var i = 0; i < str.length; i++)
{
var char = str.charAt(i);
alert(char);
}
Most if not all of the answers here are wrong because they will break whenever there is a character in the string outside the Unicode BMP (Basic Multilingual Plane). That means all Emoji will be broken.
JavaScript uses UTF-16 Unicode for all strings. In UTF-16, characters beyond the BMP are made out of two parts, called a "Surrogate Pair" and most of the answers here will process each part of such pairs individually instead of as a single character.
One way in modern JavaScript since at least 2016 is to use the new String iterator. Here's the example (almost) straight out of MDN:
var string = 'A\uD835\uDC68B\uD835\uDC69C\uD835\uDC6A';
for (var v of string) {
alert(v);
}
// "A"
// "\uD835\uDC68"
// "B"
// "\uD835\uDC69"
// "C"
// "\uD835\uDC6A"
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);
If you want to do a transformation on the text on a character level, and get the transformed text back at the end, you would do something like this:
var value = "alma";
var new_value = [...value].map((x) => x+"E").join("")
So the steps:
- Split the string into an array (list) of characters
- Map each character via a functor
- Join the resulting array of chars together into the resulting string
NOTE: If you need performance, there are probably better, more optimized solutions for this. I posted this one as a clean codestyle approach.
One more solution...
var strg= 'This is my string';
for(indx in strg){
alert(strg[indx]);
}
It is better to use the for...of statement, if the string contains unicode characters, because of the different byte size.
for(var c of "tree 木") { console.log(c); }
//"
本文标签:
stringHow can I process each letter of text using JavascriptStack Overflow
版权声明:本文标题:string - How can I process each letter of text using Javascript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人,
转载请联系作者并注明出处:http://www.betaflare.com/web/1736674441a1947102.html,
本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
for(const c of str) { ... }
. More of that further below in a quite detailed but not sufficiently upvoted answer. PS: @ARJUN's link doesn't work for me. – Max Commented Jan 27, 2019 at 16:03