I want to split following string into two parts using split function of javascript
original string is 'Average Sized' - 'Mega Church!' (with single quotes)
please mark that there is a single quote inside the string
and i want to split it by hyphen symbol so the result would be
[0] Average Sized
[1] Mega Church!
The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.
Split a String by the last Dot in JavaScript # To split a string by the last dot, call the lastIndexOf() method to get the last index of a dot in the string and use the slice() method to get two substrings - one including the characters before the last dot, and the other - the characters after the last dot.
To insert hyphens into a JavaScript string, we can use the JavaScript string's replace method. We call phone. replace with a regex that has 3 capturing groups for capturing 2 groups of 3 digits and the remaining digits respectively. Then we put dashes in between each group with '$1-$2-$3' .
To split a JavaScript string only on the first occurrence of a character, call the slice() method on the string, passing it the index of the character + 1 as a parameter. The slice method will return the portion of the string after the first occurrence of the character.
var str = "Average Sized - Mega Church!";
var arr = str.split("-");
try this:
"Average Sized - Mega Church!".split(/\s*\-\s*/g)
edit:
if you mean the original string INCLUDES the single quotes, this should work:
"'Average Sized - Mega Church!'".replace(/^'|'$/g, "").split(/\s*\-\s*/g)
if you just meant that the string is defined with single quotes, the original will work.
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