正则表达式或jQuery的某些字符后拆分字符串 [英] regex or jquery to split string after certain character

查看:285
本文介绍了正则表达式或jQuery的某些字符后拆分字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的字符串:

I have a string like this:

Franciscan圣弗朗西斯健康中心-印第安纳波利斯

Franciscan St. Francis Health - Indianapolis

我需要提取-"之后的所有内容(包括破折号本身)并在第二行中输出.如何提取-"之前的所有内容??正则表达式还是jQuery?

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

推荐答案

都没有.我只是将本机.split()函数用于字符串:

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

一旦创建了stringArray变量,就可以以任意方式输出原始字符串的片段,例如:

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 commenter'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"

.slice().join()都是JS中的本机Array方法,而join()与先前使用的.split()方法相反.

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

这篇关于正则表达式或jQuery的某些字符后拆分字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆