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 badges3 Answers
Reset to default 10Neither. 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
版权声明:本文标题:javascript - regex or jquery to split string after certain character - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1740214470a2242609.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论