Javascript - 爆炸相当于?

时间:2012-02-18 03:17:47

标签: javascript explode

所以,我有一个带分隔符的字符串| ,其中一个部分包含“123”,有没有办法找到这个部分并打印内容? 像PHP爆炸(但Javascript),然后循环找到'123'可能? :/

4 个答案:

答案 0 :(得分:18)

var string = "123|34|23|2342|234",
    arr = string.split('|'),
    i;

for(i in arr){
    if(arr[i] == 123) alert(arr[i]);
}

或者:

for(i in arr){
    if(arr[i].indexOf('123') > -1) alert(arr[i]);
}

有关基于string的操作和函数的更多信息,请参阅:

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String

答案 1 :(得分:3)

您可以在JavaScript中使用 split()

var txt = "123|1203|3123|1223|1523|1243|123",
    list = txt.split("|");

console.log(list);

for(var i=0; i<list.length; i++){
    (list[i]==123) && (console.log("Found: "+i));  //This gets its place
}

LIVE DEMO:http://jsfiddle.net/DerekL/LQRRB/

答案 2 :(得分:1)

.split相当于explode,而.join相当于implode

var myString = 'red,green,blue'; 
var myArray = myString.split(','); //explode
var section = myArray[1];
var myString2 = myArray.join(';'); //implode

答案 3 :(得分:1)

这应该这样做:

var myString = "asd|3t6|2gj|123hhh", splitted = myString.split("|"), i;
for(i = 0; i < splitted.length; i++){ // You could use the 'in' operator, too 
    if(splitted[i].match("123")){
        // Do something
        alert(splitted[i]); // Alerts the entire contents between the original |'s 
        // In this case, it will alert "123hhh". 
    }
}