admin管理员组

文章数量:1244296

I have a string like this:

Franciscan St. Francis Health - Indianapolis

I need to extract everything after '-' including the dash itself and output it in the second line..How do I extract everything before '-'?? Regex or jquery?

The string infront of '-' will be dynamic and could have varying number of letters...

I have a string like this:

Franciscan St. Francis Health - Indianapolis

I need to extract everything after '-' including the dash itself and output it in the second line..How do I extract everything before '-'?? Regex or jquery?

The string infront of '-' will be dynamic and could have varying number of letters...

Share Improve this question asked Mar 7, 2012 at 19:31 Anjana SharmaAnjana Sharma 4,7555 gold badges40 silver badges51 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 10

Neither. I would just use the native .split() function for strings:

var myString = 'Franciscan St. Francis Health - Indianapolis';
var stringArray = myString.split('-');
//at this point stringArray equals: ['Franciscan St. Francis Health ', ' Indianapolis']

Once you've crated the stringArray variable, you can output the original string's pieces in whatever way you want, for example:

alert('-' + stringArray[1]); //alerts "- Indianapolis"

Edit
To address a menter's follow-up question: "What if the string after the hyphen has another hyphen in it"?

In that case, you could do something like this:

var myString = 'Franciscan St. Francis Health - Indianapolis - IN';
var stringArray = myString.split('-');
//at this point stringArray equals: ['Franciscan St. Francis Health ', ' Indianapolis ', ' IN']

alert('-' + stringArray.slice(1).join('-')); //alerts "- Indianapolis - IN"

Both .slice() and .join() are native Array methods in JS, and join() is the opposite of the .split() method used earlier.

Regex or jquery?

False dichotomy. Use String.splitMDN

var tokens = 'Franciscan St. Francis Health - Indianapolis'.split('-');
var s = tokens.slice(1).join('-'); // account for '-'s in city name
alert('-' + s);
  • DEMO
  • join()MDN
  • slice()MDN

Probably no need for regex or jquery. This should do it:

var arr = 'Franciscan St. Francis Health - Wilkes-Barre'.split('-');
var firstLine = arr[0]
var secondLine = arr.slice(1).join('-');

Ideally, your data would be stored in two separate fields, so you don't have to worry about splitting strings for display.

本文标签: javascriptregex or jquery to split string after certain characterStack Overflow