"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Split a String in JavaScript Like PHP\'s explode() Function?

How to Split a String in JavaScript Like PHP\'s explode() Function?

Published on 2024-10-31
Browse:632

How to Split a String in JavaScript Like PHP\'s explode() Function?

Javascript Equivalent to PHP Explode()

PHP's explode() function allows you to split a string into an array based on a specific delimiter. In JavaScript, a similar functionality can be achieved using the split() method.

For instance, consider the following PHP code:

$str = '0000000020C90037:TEMP:data';
$arr = explode(':', $str);
$var = $arr[1].':'.$arr[2];

This code splits the string at the : delimiter and assigns the second and third elements of the resulting array to the variable $var.

To achieve the same functionality in JavaScript, you can use the following code:

var mystr = '0000000020C90037:TEMP:data';
var myarr = mystr.split(":");
var myvar = myarr[1]   ":"   myarr[2];

This code loads the string into the mystr variable, splits it at the : delimiter, and stores the resulting array in the myarr variable. The second and third elements of the array are then concatenated and stored in the myvar variable.

By following this approach, you can effectively "explode" a string in JavaScript and obtain the desired substring.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3