Javascript - explode equivilent?
Asked Answered
G

4

7

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

Glasses answered 18/2, 2012 at 3:17 Comment(2)
possible duplicate of Javascript Equivalent to ExplodeRoguish
Possible duplicate of Javascript Equivalent to PHP Explode()Metonymy
M
18
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.

Microvolt answered 18/2, 2012 at 3:20 Comment(5)
How do I then locate the section with "123" and echo whatever else is in the section :o?Glasses
:) the section has more than just 123 in it though, so is there like a strstr() equivilient for Javascript?Glasses
Use the match() function; see my answer below.Brasier
@King review the documentation for the JavaScript string object and it's associated methods and properties...Microvolt
var string = "123 and stuf|34|23|2342|234", arr = string.split('|'), i; for(i in arr){ if(arr[i].search(123) != -1) alert(arr[i]); } Glasses
C
3

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/

Cyclopedia answered 18/2, 2012 at 3:22 Comment(0)
T
1

.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
Tolland answered 18/2, 2012 at 3:22 Comment(0)
B
1

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". 
    }
}
Brasier answered 18/2, 2012 at 3:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.