user1937021
user1937021

Reputation: 10811

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

Upvotes: 2

Views: 72

Answers (6)

m0meni
m0meni

Reputation: 16455

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

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

Upvotes: 2

Avinash Raj
Avinash Raj

Reputation: 174874

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'

Upvotes: 2

hek2mgl
hek2mgl

Reputation: 158270

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.

Upvotes: 1

atmd
atmd

Reputation: 7490

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.

Upvotes: 4

Maroun
Maroun

Reputation: 96016

* 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_.

Upvotes: 1

user1880062
user1880062

Reputation: 85

In general the split solution is better in performance compared to using a regular expression.

Upvotes: 1

Related Questions