最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - How to remove the last portion of string in JavaScript? - Stack Overflow

programmeradmin1浏览0评论

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?

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.

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?

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.

Share Improve this question edited May 30, 2014 at 21:37 E-Riz 32.9k13 gold badges104 silver badges152 bronze badges asked May 30, 2014 at 21:22 UnicornUnicorn 1091 silver badge11 bronze badges 3
  • 2 What have you tried? Please show some effort/research/code. Have you tried googling "JavaScript string manipulations" ? – suff trek Commented May 30, 2014 at 21:23
  • i tried the following: var newxx = xx.replace("&IDshow=", ""); but because the numbers after = can be vary, so i dont know how to tackle it. thank you, – Unicorn Commented May 30, 2014 at 21:27
  • 1 You should update your post, not comment – cr0ss Commented May 30, 2014 at 21:28
Add a comment  | 

4 Answers 4

Reset to default 11

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. 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. 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. 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 "&". 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. 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).

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

split is fast to use if a string should be broken up into several strings.

substring The substring-method of the string object returns a part of the string. It can be used with indexOf (that searches for a specified string) to determinate what part of the string that should be returned. This method was suggested by Jay Blanchard. The indexOf returns -1 if the string it searched for wasn't found. 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. 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.

In my test I started with a list of 100 songs titles, and added different trailing strings. 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. 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. And in Internet explorer it is the slowest.

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.

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. 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. But if there are multiple separators it is faster in Chrome and Opera. In Internet explorer it is always faster than without a limit.

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

split without limit (green)

Almost the same as split to array but slightly faster in Chrome and 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. It is the fastest method in all tested browsers. In Firefox it is almost twice as fast as the other methods.

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.

One technique is using 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() -

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;

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

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. (I'm always doing performance checks just for fun).

HERE's the test performance.

Ran on Chrome 27.0.1453.

Here's the benchmark for all tests I did:

  1. regex was 0,81% slower
  2. regex and split were equal
  3. regex was 4% slower
  4. regex was 8% faster
  5. regex was 20% faster
  6. regex was 8% faster
  7. regex was 0,17% slower
  8. regex was 6% faster

One can only conclude that regex is a bit faster.

发布评论

评论列表(0)

  1. 暂无评论