简体   繁体   中英

Return specific part of string in Javascript

I would like to manipulate this following string: 20_hbeu50272359_402_21

so that I am left with only hbeu50272359 is there a way to how could I delete those outer numbers? Not sure how to go about it.

The strings may also take this format:

hbeu50272359_402_21

You can use split

"20_hbeu50272359_402_21".split('_')[1]

The above splits your string based on the _ char, then use [1] to select the part you want (in the returned array or ["20", "hbeu50272359", "402", "21"] )

This of course would asume that your strings always follow the same format. if not you could use a regEx match with what appears to be a prefix of hbeu . Something like /(hbeu[0-9]+)/ But I'd need more info to give a better approach to the split method

UPDATE:

based on your update you could do a regex match like:

var stuffWeWant = "20_hbeu50272359_402_21".match(/(hbeu[0-9]+)/)[0];
// this will work regardless of the string before and after hbeu50272359.

(?!\\d)[^_]+ will work on both strings and it doesn't require the second string to start with hbeu .

https://regex101.com/r/zF0iR5/3

You could use string.replace function also. ie, replace

  • One or more digits plus the following underscore symbol at the start,

  • OR

  • underscore plus one or more digits followed by another underscore or end of the line anchor

with an empty string.

> "20_hbeu50272359_402_21".replace(/_\d+(?=_|$)|^\d+_/g, "")
'hbeu50272359'
> "hbeu50272359_402_21".replace(/_\d+(?=_|$)|^\d+_/g, "")
'hbeu50272359'

通常,与使用正则表达式相比,拆分解决方案的性能更好。

* is greedy , the engine repeats it as many times as it can, so the regex continues to try to match the _ with next characters, resulting with matching

_hbeu50272359_402_21

In order to make it ungreedy, you should add an ? :

_(.*?)_

Now it'll match the first _somecharacters_ .

I would use String.replace() for that:

var s = "20_hbeu50272359_402_21";
var part = s.replace(/.*?_(.*?)_.*/, '$1');

The search pattern matches any char .* until the next occurrence of a _ . Using the ungreedy quantifier ? makes sure it does not match any char until the last _ in the string. The it captures the text until the next _ into a capturing group. (.*?) . Then the next _ and the remaining string is matched.

The replace pattern uses $1 to address the contents of the first capturing group and throws away the remaining match.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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