我想提醒字符串的每个字母,但我不确定如何做到这一点。

如果我有:

var str = 'This is my string';

我希望能够分别提醒T h I s等等。这只是我正在研究的一个想法的开始,但我需要知道如何分别处理每个字母。

我在想,我可能需要在测试字符串的长度后使用分割函数。

我该怎么做呢?


当前回答

当我需要写短代码或一行代码时,我使用这个“hack”:

'Hello World'.replace(/./g, function (char) {
    alert(char);
    return char; // this is optional 
});

它不会计算换行,这可能是好事,也可能是坏事。如果你想包含换行符,替换:/。/ with /[\S\ S]/。您可能看到的其他一行程序可能使用.split(),这存在许多问题

其他回答

如果你想动画每个字符,你可能需要用span元素来包装它;

var $demoText = $("#demo-text");
$demoText.html( $demoText.html().replace(/./g, "<span>$&amp;</span>").replace(/\s/g, " "));

我认为这是最好的方法,然后处理张成的空间。(例如TweenMax)

TweenMax.staggerFromTo( $demoText.find(“span”), 0.2, {autoAlpha:0}, {autoAlpha:1}, 0.1 );

在ES6 / ES2015中,你可以用迭代器遍历字符串,就像你在

的象征。迭代器中数

var str = 'Hello'; var it = str[Symbol.iterator](); 对于(let v of it) { console.log (v) } / /“H” / /“e” / /“l” / /“l” / /“o”

它是一种声明式风格。优势是什么?您不必关心如何访问字符串的每个元素。

如果你想在字符级别上对文本进行转换,并在结束时获得转换后的文本,你会这样做:

var value = "alma";
var new_value = [...value].map((x) => x+"E").join("")

步骤如下:

将字符串拆分为字符数组(列表) 通过函子映射每个字符 将生成的字符数组连接到生成的字符串中

注意:如果您需要性能,可能有更好、更优化的解决方案。我把这个作为一个干净的代码风格的方法发布。

New JS允许这样做:

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

可能不止是解决了。只是想提供另一个简单的解决方案:

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);
});