Mo.
Mo.

Reputation: 42583

JavaScript RegExp: Retrieve part of a String using RegExp?

I have a String with the value of something like so: "H798asdhka80:124htg"

I want to retrieve from this string (and similarly structured strings) every character before the colon ":" so my new string would look like this: H798asdhka80

What would the code to do this look like?

Thanks

Upvotes: 0

Views: 109

Answers (5)

KooiInc
KooiInc

Reputation: 123006

Use substr:

var str = "H798asdhka80:124htg",
    strpart = str.substr(0,str.indexOf(':'));

or slice

var str = "H798asdhka80:124htg",
    strpart = str.slice(0,str.indexOf(':'));

or split

var strpart = "H798asdhka80:124htg".split(/:/)[0];

or match

var str = "H798asdhka80:124htg".match(/(^.+)?:/)[1];

or replace

var str = "H798asdhka80:124htg".replace(/:.+$/,'');

or create a more generic String.prototype extension

String.prototype.sliceUntil = function(str){
  var pos = this.indexOf(str);
  return this.slice(0, (pos>-1 ? pos : this.length));
}
var str = "H798asdhka80:124htg".sliceUntil(':124');

Upvotes: 4

mistapink
mistapink

Reputation: 1956

"H798asdhka80:124htg".split(':')[0]

Upvotes: 2

Some Guy
Some Guy

Reputation: 16210

You don't really need a RegExp for this. This should work for you:

str.split(':')[0];

Anyway, the other way would be to replace the unneeded part of the string with a regular expression, like this:

str.replace(/:.+$/, '');

Demo

Upvotes: 0

epascarello
epascarello

Reputation: 207557

A reg exp answer, match anything from the start of the string to the colon.

var str = "H798asdhka80:124htg";
var txt = str.match(/^[^:]+/);

Upvotes: 3

Oriol
Oriol

Reputation: 288690

use

var str="H798asdhka80:124htg".split(':')[0]

Using split(':') you get the array ["H798asdhka80","124htg"]. And then use only the first element of that array.

Upvotes: 6

Related Questions