I have problem when I want to separate my string in JavaScript, this is my code :
var str= 'hello.json';
str.slice(0,4); //output hello
str.slice(6,9); //output json
the problem is when i want to slice second string ('json') I should create another slice too.
I want to make this code more simple , is there any function in JavaScript like explode function in php ?
If you want to explode or split a string from a certain character or separator you can use the JavaScript split() method. The following example will show you how to split a string at each blank space. The returned value will be an array, containing the splitted values.
PHP Explode function breaks a string into an array. PHP Implode function returns a string from an array.
The explode() function breaks a string into an array. Note: The "separator" parameter cannot be an empty string. Note: This function is binary-safe.
1) Convert String to Array using explode()explode() method is one of the built-in function in PHP which can be used to convert string to array. The explode() function splits a string based on the given delimiter. A delimiter acts as a separater and the method splits the string where the delimiter exists.
You can use split()
var str = 'hello.json';
var res = str.split('.');
document.write(res[0] + ' ' + res[1])
or use substring()
and indexOf()
var str = 'hello.json';
document.write(
str.substring(0, str.indexOf('.')) + ' ' +
str.substring(str.indexOf('.') + 1)
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With