简体   繁体   English

如何在JavaScript中删除字符串的最后一部分?

[英]How to remove the last portion of string in JavaScript?

I have a few strings; 我有几串; they can be, for example: 它们可以是,例如:

1. artist_submission_design&IDshow=79025 OR
2. artist_design&IDshow=102 OR
3. status_design_001&IDshow=1

How do I remove EVERYTHING after "&" with javascript or jQuery? 如何使用JavaScript或jQuery删除“&”之后的所有内容?

Here is what I have tried: 这是我尝试过的:

var newxx = xx.replace("&IDshow=", "");

but it doesn't work because the numbers after = can vary, so I don't know how to tackle it. 但这不起作用,因为=之后的数字可能会有所不同,因此我不知道如何解决。

There are several ways to remove the last portion of a string. 有几种删除字符串最后部分的方法。 All of them have pros and cons. 他们都有优点和缺点。

Assume that we have this string: 假设我们有以下字符串:

var myString = "artist_submission_design&IDshow=79025";

replace 更换

The replace -method of the string object replaces a part of the string with another It takes two arguments. 字符串对象的replace -method方法将字符串的一部分替换为另一部分。它带有两个参数。 The fist is either a string or a regular expression that describes what part of the string that should be replaced. 第一拳是一个字符串或一个正则表达式,它描述应替换字符串的哪一部分。 The second argument is used to replace the matched content. 第二个参数用于替换匹配的内容。 It could be a string or a function. 它可以是字符串或函数。

In the example below, the match is made with a regular expression that matches the & -character and every character after that, and the match will be replaced with an empty string. 在下面的示例中,匹配是使用与&字符及之后的每个字符匹配的正则表达式进行的,并且匹配项将替换为空字符串。

var result = myString.replace(/&.*/,"");

A regular expression is flexible, and you can make complicated pattern matching. 正则表达式非常灵活,您可以进行复杂的模式匹配。 But it can be slow to execute. 但是执行起来可能很慢。

split 分裂

The split -method of the string object splits a string in one or more strings and returns an array with the strings. 字符串对象的split方法将一个字符串拆分为一个或多个字符串,并返回包含这些字符串的数组。 It takes one or two arguments. 它需要一个或两个参数。 The first one is the separator , the string that it should split on. 第一个是分隔符 ,即应该分割的字符串。 It could be a single character or a multi-character str ing. 它可以是单个字符或多个字符的字符串。 The second argument limit is optional, and limits how many strings that will be returned in the array. 第二个参数limit是可选的,它限制了数组中将返回的字符串数。 It matters if the separator is repeated in the input string. 是否在输入字符串中重复分隔符很重要。 For example "songname&artist=name&album=album&label=label" will return an array with 4 strings if the separator is "&". 例如,如果分隔符为“&”,则“ songname&artist = name&album = album&label = label”将返回包含4个字符串的数组。 If you are only interested in the first string, there is no reason to get an array with multiple strings. 如果只对第一个字符串感兴趣,则没有理由获取包含多个字符串的数组。

In the example below, myString is split on every & , but we limit it to one string. 在下面的示例中,myString在每个&上拆分,但我们将其限制为一个字符串。 And since split returns an array, and we are only interested in the first element of the array I get the first element of the array with [0] (in javascript the index of arrays is zero-based). 而且由于split返回一个数组,并且我们只对数组的第一个元素感兴趣,因此我将数组的第一个元素设为[0] (在javascript中,数组的索引从零开始)。

var result= myString.split('&',1)[0];

split is fast to use if a string should be broken up into several strings. 如果将一个字符串分解成几个字符串,则split可以快速使用。

substring The substring -method of the string object returns a part of the string. substring字符串对象的substring方法将返回字符串的一部分。 It can be used with indexOf (that searches for a specified string) to determinate what part of the string that should be returned. 它可以与indexOf (用于搜索指定的字符串)一起使用,以确定应返回字符串的哪一部分。 This method was suggested by Jay Blanchard . Jay Blanchard提出了这种方法。 The indexOf returns -1 if the string it searched for wasn't found. 如果找不到要搜索的字符串,则indexOf返回-1。 Since we in that case wants the whole string we must test for that case and adjust the end position. 由于在那种情况下我们需要整个字符串,因此我们必须测试这种情况并调整结束位置。

var pos = myString.indexOf('&');
if ( pos < 0 ) pos = myString.length;
var result = myString.substring(0, pos);

While it is a little more to type the performance is great in all tested browsers. 尽管键入的内容多一点,但在所有经过测试的浏览器中,性能都很棒。

So which one should I use? 那么我应该使用哪一个呢?

It depends on what you are doing, and how much data you are processing. 这取决于您正在做什么以及要处理多少数据。 cr0ss did setup a performance test on jsperf . cr0ss确实在jsperf上设置了性能测试。 I added some more tests and later even more tests with more data. 我添加了更多测试 ,后来又添加了更多数据的更多测试 The latest test is made with Chrome 35, Firefox 29, Opera 21 and Internet Explorer 11 on the same computer. 最新测试是在同一台计算机上使用Chrome 35,Firefox 29,Opera 21和Internet Explorer 11进行的。

性能 In my test I started with a list of 100 songs titles, and added different trailing strings. 测试中,我首先列出了100首歌曲,然后添加了不同的结尾字符串。 That way I got strings with nothing extra, and strings with one or more separators. 这样一来,我得到的字符串就没有多余的东西了,而且字符串还带有一个或多个分隔符。

regex (blue) 正则表达式 (蓝色)

Using replace with a regular expression allows you to handle complicated cases. 在正则表达式中使用replace可以处理复杂的情况。 But it comes with a price, since regular expressions can be slow. 但这要付出代价,因为正则表达式可能很慢。 But with the tested data it is faster than split in Chrome and Opera, and about the same speed in Firefox. 但是使用测试的数据,它比在Chrome和Opera中拆分的速度快,并且在Firefox中的速度差不多。 And in Internet explorer it is the slowest. 在Internet Explorer中,它是最慢的。

var result = input.replace(/&.*/, "");

split to array (red) 拆分为数组 (红色)

split to array and split without limit is almost the same. 拆分为数组无限制拆分几乎相同。 It differs in the temporary variable. 临时变量不同。 With the tested data it is slower than regex in Chrome and Opera, almost the same speed in Firefox, and medium in Internet Explorer. 使用测试的数据,它在Chrome和Opera中的速度比regex慢,在Firefox中的速度几乎相同,而在Internet Explorer中的速度则中等。

var array = test.input.split('&');
var result = array[0];

split with limit (yellow) 极限分割 (黄色)

split has an optional second argument, that limits how many strings that can be returned. split具有可选的第二个参数,该参数限制可以返回的字符串数。 If the input string has more than one separator, this has potential to be faster. 如果输入字符串具有多个分隔符,则可能会更快。

If there is only one separator in the input string, this is much slower in Chrome, Firefox and Opera. 如果输入字符串中只有一个分隔符,则在Chrome,Firefox和Opera中,这要慢得多。 But if there are multiple separators it is faster in Chrome and Opera. 但是,如果有多个分隔符,则在Chrome和Opera中会更快。 In Internet explorer it is always faster than without a limit. 在Internet Explorer中,它总是比没有限制更快。

var result = myString .split('&',1)[0];

split without limit (green) 无限分割 (绿色)

Almost the same as split to array but slightly faster in Chrome and Opera. 拆分为数组几乎相同,但在Chrome和Opera中则稍快一些。

var reusult = myString.split('&')[0];

substring fixed 子串固定

This version is based on the answer from Jay Blanchard that was using substring but this version returns the whole string if the separator isn't found. 该版本基于Jay Blanchard的答案,该答案使用substring但如果未找到分隔符,则此版本将返回整个字符串。 It is the fastest method in all tested browsers. 在所有经过测试的浏览器中,这是最快的方法。 In Firefox it is almost twice as fast as the other methods. 在Firefox中,它的速度几乎是其他方法的两倍。

var idx = myString.indexOf('&');
var result = myString.substring(0, idx < 0 ? string.length: idx);

Conclusion 结论

The results depends on what data you are using. 结果取决于您使用的数据。 There are too much caching, branch-predictions and other things going on below the surface to make a good recommendation based on these tests. 表面下有太多的缓存,分支预测和其他内容,因此无法根据这些测试提出良好的建议。 As seen from the profiling it matters what browser you are using. 从配置文件中可以看出,所用的浏览器很重要。 If you have much data to process you could profile what method that is faster with the data you have. 如果要处理的数据很多,则可以使用所拥有的数据来分析哪种方法更快。

With the tested data the substring -method is by far the fastest in all tested browsers, and it makes sense since it is simple. 对于测试过的数据, substring -method到目前为止是所有测试过的浏览器中最快的,并且它很简单,因此很有意义。

One technique is using split() 一种技术是使用split()

var myString = 'artist_submission_design&IDshow=79025';
var splitString = myString.split('&');
var newString = splitString[0]; // returns artist_submission_design

Another technique uses substring() and indexOf() - 另一种技术使用substring()indexOf() -

var string = 'artist_submission_design&IDshow=79025';
var foo = string.substring(0, string.indexOf('&')); // foo is now "artist_submission_design"

use the .split method in javascript... here's an example; 在javascript中使用.split方法...这是一个示例;

var string = 'artist_submission_design&IDshow=79025';
//split at the & character
var myArray = string.split('&');

//everything before and after will be put in an array like this;
myArray[0] => 'artist_submission_design'
myArray[1] => 'IDshow=79025'

//this will store everything in myArray[0] in a variable called formatedString
var formattedString = myArray[0];

this will work for all of them and remove everything after the & regardless of letters/numbers, although this could have been found easily... 这将适用于所有人,并删除&后面的所有内容,而不考虑字母/数字,尽管可以很容易地找到它...

javascript split javascript拆分

This is not an answer, this is just complementing the answers before. 这不是答案,只是对之前答案的补充。

I was simply curious of which would be more efficient: regex or split . 我只是很好奇哪个会更有效: regexsplit (I'm always doing performance checks just for fun). (我总是为了娱乐而进行性能检查)。

HERE's the test performance. 这里是测试性能。

Ran on Chrome 27.0.1453. 在Chrome 27.0.1453上运行。

Here's the benchmark for all tests I did: 这是我所做的所有测试的基准:

  1. regex was 0,81% slower regex 慢了 0.81%
  2. regex and split were equal regexsplit 相等
  3. regex was 4% slower regex 慢了4%
  4. regex was 8% faster regex 快了8%
  5. regex was 20% faster regex 快20%
  6. regex was 8% faster regex 快了8%
  7. regex was 0,17% slower regex 慢了0.17%
  8. regex was 6% faster regex 快了6%

One can only conclude that regex is a bit faster. 只能得出结论, regex要快一点。

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

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