Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - explode equivilent?

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? :/

like image 702
Goulash Avatar asked Feb 18 '12 03:02

Goulash


2 Answers

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

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

Or:

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

Or:

arr.forEach((el, i, arr) => if(arr[i].indexOf('123') > -1) alert(arr[i]) }

Or:

arr.forEach((el, i, arr) => if(el == '123') alert(arr[i]) }

Or:

const arr = "123|34|23|2342|234".split('|')

if(arr.some(el=>el == "123")) alert('123')

More information on string and Array memeber functions.

like image 121
Alex Avatar answered Sep 22 '22 12:09

Alex


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/

like image 45
Derek 朕會功夫 Avatar answered Sep 19 '22 12:09

Derek 朕會功夫