简体   繁体   English

提取字符串部分的最有效方法

[英]Most efficient way to extract parts of string

I have a bunch of strings in the format 'TYPE_1_VARIABLE_NAME'. 我有一堆格式为“ TYPE_1_VARIABLE_NAME”的字符串。

The goal is to get 3 variables in the form of: 目标是获得以下形式的3个变量:

varType = 'TYPE',
varNumber = '1',
varName = 'VARIABLE_NAME'

What's the most efficient way of achieving this? 最有效的方法是什么?

I know I can use: 我知道我可以使用:

var firstUnderscore = str.indexOf('_')
varType = str.slice(0, firstUnderscore))
varNumber = str.slice(firstUnderscore+1,firstUnderscore+2)
varName = str.slice(firstUnderscore+3)

but this feels like a poor way of doing it. 但这感觉很糟糕。 Is there a better way? 有没有更好的办法? RegEx? 正则表达式?

Or should I just rename the variable to 'TYPE_1_variableName' and do a: 或者我应该将变量重命名为“ TYPE_1_variableName”并执行以下操作:

varArray = str.split('_')

and then get them with: 然后用:

varType = varArray[0],
varNumber = varArray[1],
varName = varArray[2]

Any help appreciated. 任何帮助表示赞赏。 jQuery also ok. jQuery也可以。

Regex solution 正则表达式解决方案

Given that the first and second underscores are the delimiters, this regex approach will extract the parts (allowing underscores in the last part): 假定第一个和第二个下划线是定界符,则此正则表达式方法将提取各部分(在最后一部分中允许使用下划线):

//input data
var string = 'TYPE_1_VARIABLE_NAME';

//extract parts using .match()
var parts = string.match(/([^_]+)_([^_]+)_([^$]+)/);

//indexes 1 through 3 contains the parts
var varType = parts[1];
var varNumber = parts[2];
var varName = parts[3];

Given that the first variable consists of characters and the second of digits, this more specific regex could be used instead: 假设第一个变量由字符组成,第二个变量由数字组成,则可以改用以下更具体的正则表达式:

var parts = string.match(/(\w+)_(\d)_(.+)/);

Non-regex solution 非正则表达式解决方案

Using .split('_') , you could do this: 使用.split('_') ,您可以这样做:

//input data
var string = 'TYPE_1_VARIABLE_NAME';

//extract parts using .split()
var parts = string.split('_');

//indexes 0 and 1 contain the first parts
//the rest of the parts array contains the last part
var varType = parts[0];
var varNumber = parts[1];
var varName = parts.slice(2).join('_');

In matters of efficiency, both approaches contain about the same amount of code. 在效率方面,两种方法都包含大约相同数量的代码。

You could use regex and split 您可以使用正则表达式和split

 var string='TYPE_1_VARIABLE_NAME'; var div=string.split(/^([AZ]+)_(\\d+)_(\\w+)$/); console.log('type:'+div[1]); console.log('num:'+div[2]); console.log('name:'+div[3]); 

Here's an answer I found here : 这是我在这里找到的答案:

var array = str.split('_'),
    type = array[0], number = array[1], name = array[2];

ES6 standardises destructuring assignment, which allows you to do what Firefox has supported for quite a while now: ES6使销毁分配标准化,这使您可以执行Firefox相当长一段时间以来支持的工作:

var [type, number, name] = str.split('_');

You can check browser support using Kangax's compatibility table . 您可以使用Kangax的兼容性表检查浏览器支持。

Here's a sample Fiddle 这是样本小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM