0

There is a string like below

var indicator = -45(www.anyweb.com)

the number -45 can be any number. How can I take out only the -45 separately in javascript? Assume the format will always be like this

number(url)
1
  • With parseInt(indicator) if you want an integer and parseFloat(indicator) if you want a 'float' Commented May 31, 2016 at 16:55

4 Answers 4

2

Simply use parseInt. As the (mozilla) docs say:

If parseInt encounters a character that is not a numeral in the specified radix, it ignores it and all succeeding characters and returns the integer value parsed up to that point.

That means: if the first part looks like a number, it gets converted and the rest is thrown away.

parseInt("-24(foo.com)")
gives
-24

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

Comments

1

How about something like this:

indicator = indicator.replace(/[0-9]/g, '');

or

indicator = indicator.replace(/\d+/g, '');

If you are looking to just get the numbers then try something like this:

indicator = indicator.match(/[0-9]+/g);

2 Comments

Wouldn't that get rid of the number? I think they want the number without the URL.
@MikeC I read that wrong then. I thought take out number meant removing the number from the url.
0

Assuming this is an actual string (i.e. wrapped in quotes), you could strip the number out via a simple regular expression, which would check if the beginning of the string started with a number :

// Your original string
var indicator = "-45(www.anyweb.com)";
// Access your number
var number = indicator.match(/^\-?\d+/)[0];  // yields "-45"
// Now remove it from your original string
indicator = indicator.replace(/^\-?\d+/,''); // yields "(www.anyweb.com)"

Example

// Your original string
var indicator = "-45(www.anyweb.com)";
// Access your number
var number = indicator.match(/^\-?\d+/)[0];
// Now remove it from your original string
indicator = indicator.replace(/^\-?\d+/,'');
console.log('indicator: ' + indicator + ', number: ' + number);

Comments

0

Use the split method and take the first element from the array:

var indicator = "-45(www.anyweb.com)";
var fubar = indicator.split("(");
console.log(fubar[0]); // returns   >> "-45"

2 Comments

This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From Review
@CarlMarkham better now?

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.