Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

split string by hyphen in javascript

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!
like image 752
Hunt Avatar asked Feb 11 '11 07:02

Hunt


People also ask

How to split string value using JavaScript?

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.

How to split string at period JavaScript?

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.

How do you add a hyphen in JavaScript?

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' .

How do you split a string on the first instance of a character?

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.


2 Answers

var str = "Average Sized - Mega Church!";
var arr = str.split("-");
like image 129
Silagy Avatar answered Oct 20 '22 10:10

Silagy


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.

like image 43
Stephen Avatar answered Oct 20 '22 10:10

Stephen