Javascript - explode equivilent?

ぐ巨炮叔叔 提交于 2019-12-19 02:27:14

问题


So, I have a string with the delimiter | , one of the sections contains "123", is there a way to find this section and print the contents? something like PHP explode (but Javascript) and then a loop to find '123' maybe? :/


回答1:


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

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

Or:

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

For more information on string based manipulation and functions see:

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




回答2:


You can use split() in JavaScript:

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/




回答3:


This should do it:

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". 
    }
}



回答4:


.split is the equivalent of explode, whereas .join is the equivalent of implode.

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


来源:https://stackoverflow.com/questions/9338205/javascript-explode-equivilent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!