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? :/
Asked
Active
Viewed 2.7k times
7
-
3possible duplicate of [Javascript Equivalent to Explode](http://stackoverflow.com/questions/4514323/javascript-equivalent-to-explode) – Michael Berkowski Feb 18 '12 at 03:29
-
Possible duplicate of [Javascript Equivalent to PHP Explode()](https://stackoverflow.com/questions/4514323/javascript-equivalent-to-php-explode) – James K. Aug 16 '17 at 18:25
4 Answers
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')

Alex
- 34,899
- 5
- 77
- 90
-
How do I then locate the section with "123" and echo whatever else is in the section :o? – Goulash Feb 18 '12 at 03:21
-
:) the section has more than just 123 in it though, so is there like a strstr() equivilient for Javascript? – Goulash Feb 18 '12 at 03:24
-
-
@King review the documentation for the `JavaScript` string object and it's associated `methods` and `properties`... – Alex Feb 18 '12 at 03:30
-
`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]); } ` – Goulash Feb 18 '12 at 03:35
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/

Derek 朕會功夫
- 92,235
- 44
- 185
- 247
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

A J
- 3,970
- 14
- 38
- 53

Chad von Nau
- 4,316
- 1
- 23
- 34
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".
}
}

wecsam
- 2,651
- 4
- 25
- 46