0

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

5 Answers 5

6

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Where is the reg exp like the poster asked? :)
@epascarello There's no need to use reg exp, I think it's better and simpler this way
4

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');

Comments

3

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

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

Comments

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.