javascript 正则表达式或 jquery 在特定字符后拆分字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9607846/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
regex or jquery to split string after certain character
提问by Anjana Sharma
I have a string like this:
我有一个这样的字符串:
Franciscan St. Francis Health - Indianapolis
Franciscan St. Francis Health - 印第安纳波利斯
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?
我需要提取“-”之后的所有内容,包括破折号本身并将其输出到第二行..如何提取“-”之前的所有内容?正则表达式还是jquery?
The string infront of '-' will be dynamic and could have varying number of letters...
'-' 前面的字符串将是动态的,并且可能有不同数量的字母...
回答by maxedison
Neither. I would just use the native .split()
function for strings:
两者都不。我只会.split()
对字符串使用本机函数:
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:
一旦你创建了stringArray
变量,你可以以任何你想要的方式输出原始字符串的片段,例如:
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"
Both .slice()
and .join()
are native Array
methods in JS, and join()
is the opposite of the .split()
method used earlier.
两个.slice()
和.join()
原产Array
于JS的方法,和join()
是的相反.split()
方法之前使用。
回答by paislee
Regex or jquery?
正则表达式还是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);
回答by gstroup
Probably no need for regex or jquery. This should do it:
可能不需要正则表达式或 jquery。这应该这样做:
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.
理想情况下,您的数据将存储在两个单独的字段中,因此您不必担心拆分字符串以进行显示。