如何获得指定字符的位置? [英] How to get the positions of an specified char?

查看:73
本文介绍了如何获得指定字符的位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串 Hello World。我想从字符串中获取char l的位置。

I have a string "Hello World". I want the positions of the char "l" from the String.

我的代码如下:

str = "Hello World";
pos = str.search(/l/g);
out.value = pos;

此代码的结果为2,但所需结果为2,3,9。

The result of this code is 2, but the wanted result is 2,3,9.

如何获得此结果?

编辑:谢谢您的帮助。

但是现在我想获得(2 + 1 * 105)+(3 + 1 * 105)+(9 + 1 * 105)的总和。

But now i want to get the sum of (2+1*105) + (3+1*105) + (9+1*105).

您能再帮我吗?

推荐答案

做一个小函数呢?

str = "Hello World";
find = (function(str,c){
    results = []  
    for(i=0;i<str.length;i++){
       if (str[i].toLowerCase()===c)
           results.push(i)
    }
    return results
});
find(str,'l')

这里是工作提琴: http://jsfiddle.net/bx8sj0gv/

这篇关于如何获得指定字符的位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆