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)
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
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);
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);
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"
parseInt(indicator)if you want an integer andparseFloat(indicator)if you want a 'float'