Javascript 在javascript中用连字符分割字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4966582/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 14:59:23  来源:igfitidea点击:

split string by hyphen in javascript

javascriptstringsplit

提问by Hunt

I want to split following string into two parts using split function of javascript

我想使用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!

采纳答案by Stephen

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.

如果你只是想用单引号定义字符串,那么原来的就可以了。

回答by Silagy

var str = "Average Sized - Mega Church!";
var arr = str.split("-");

回答by Sachin Shanbhag

var str = "Average Sized - Mega Church!";
var arr = [];

arr = str.split('-');

回答by Ishara Sandun

Easiest Method is

最简单的方法是

var arr = "'Average Sized'-'Mega Church!'".replace(/'/ig,"").split("-")