javascript - get two numbers from a string - javascript

I have a string like:
text-345-3535
The numbers can change.
How can I get the two numbers from it and store that into two variables?

var str = "text-345-3535"
var arr = str.split(/-/g).slice(1);
Try it out: http://jsfiddle.net/BZgUt/
This will give you an array with the last two number sets.
If you want them in separate variables add this.
var first = arr[0];
var second = arr[1];
Try it out: http://jsfiddle.net/BZgUt/1/
EDIT:
Just for fun, here's another way.
Try it out: http://jsfiddle.net/BZgUt/2/
var str = "text-345-3535",first,second;
str.replace(/(\d+)-(\d+)$/,function(str,p1,p2) {first = p1;second = p2});

var m = "text-345-3535".match(/.*?-(\d+)-(\d+)/);
m[1] will hold "345" and m[2] will have "3535"

If you're not accustomed to regular expressions, #patrick dw's answer is probably better for you, but this should work as well:
var strSource = "text-123-4567";
var rxNumbers = /\b(\d{3})-(\d{4})\b/
var arrMatches = rxNumbers.exec(strSource);
var strFirstCluster, strSecondCluster;
if (arrMatches) {
strFirstCluster = arrMatches[1];
strSecondCluster = arrMatches[2];
}
This will extract the numbers if it is exactly three digits followed by a dash followed by four digits. The expression can be modified in many ways to retrieve exactly the string you are after.

Try this,
var text = "text-123-4567";
if(text.match(/-([0-9]+)-([0-9]+)/)) {
var x = Text.match(/([0-9]+)-([0-9]+)/);
alert(x[0]);
alert(x[1]);
alert(x[2]);
}
Thanks.

Another way to do this (using String tokenizer).
int idx=0; int tokenCount;
String words[]=new String [500];
String message="text-345-3535";
StringTokenizer st=new StringTokenizer(message,"-");
tokenCount=st.countTokens();
System.out.println("Number of tokens = " + tokenCount);
while (st.hasMoreTokens()) // is there stuff to get?
{words[idx]=st.nextToken(); idx++;}
for (idx=0;idx<tokenCount; idx++)
{System.out.println(words[idx]);}
}
output
words[0] =>text
words[1] => 345
words[2] => 3535

Related

Javascript getting number from string

I have a string:
var example = 'sorted-by-' + number;
Where number variable can be any positive integer. I don't know how to reverse this process, not knowing how many digits this number has. I want to get from example string a number at the end.
var outputNumber = example.substring(10);
This is the simple solution because example string always start with 'sorted-by-'.
let num = + string.substr(10);
You can use String#replace function to replace sorted-by- to empty string and after that convert left part to a number:
var example = 'sorted-by-' + 125;
var num = +example.replace('sorted-by-', '');
console.log(num);
You can split string at - and get last element using pop().
var example = 'sorted-by-' + 100.99
var n = +(example.split('-').pop())
console.log(n)
You can also use regex for this.
var number = 245246245;
var example = 'sorted-by-' + number;
var res = example.match(/^sorted-by-(\d+)/);
console.log(+res[1]);

regex to find specific strings in javascript

disclaimer - absolutely new to regexes....
I have a string like this:
subject=something||x-access-token=something
For this I need to extract two values. Subject and x-access-token.
As a starting point, I wanted to collect two strings: subject= and x-access-token=. For this here is what I did:
/[a-z,-]+=/g.exec(mystring)
It returns only one element subject=. I expected both of them. Where i am doing wrong?
The g modifier does not affect exec, because exec only returns the first match by specification. What you want is the match method:
mystring.match(/[a-z,-]+=/g)
No regex necessary. Write a tiny parser, it's easy.
function parseValues(str) {
var result = {};
str.split("||").forEach(function (item) {
var parts = item.split("=");
result[ parts[0] /* key */ ] = parts[1]; /* value */
});
return result;
}
usage
var obj = parseValues("subject=something||x-access-token=something-else");
// -> {subject: "something", x-access-token: "something-else"}
var subj = obj.subject;
// -> "something"
var token = obj["x-access-token"];
// -> "something-else"
Additional complications my arise when there is an escaping schema involved that allows you to have || inside a value, or when a value can contain an =.
You will hit these complications with regex approach as well, but with a parser-based approach they will be much easier to solve.
You have to execute exec twice to get 2 extracted strings.
According to MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec
If your regular expression uses the "g" flag, you can use the exec() method multiple times to find successive matches in the same string.
Usually, people extract all strings matching the pattern one by one with a while loop. Please execute following code in browser console to see how it works.
var regex = /[a-z,-]+=/g;
var string = "subject=something||x-access-token=something";
while(matched = regex.exec(string)) console.log(matched);
You can convert the string into a valid JSON string, then parse it to retrieve an object containing the expected data.
var str = 'subject=something||x-access-token=something';
var obj = JSON.parse('{"' + str.replace(/=/g, '":"').replace(/\|\|/g, '","') + '"}');
console.log(obj);
I don't think you need regexp here, just use the javascript builtin function "split".
var s = "subject=something1||x-access-token=something2";
var r = s.split('||'); // r now is an array: ["subject=something1", "x-access-token=something2"]
var i;
for(i=0; i<r.length; i++){
// for each array's item, split again
r[i] = r[i].split('=');
}
At the end you have a matrix like the following:
y x 0 1
0 subject something1
1 x-access-token something2
And you can access the elements using x and y:
"subject" == r[0][0]
"x-access-token" == r[1][0]
"something2" == r[1][1]
If you really want to do it with a pure regexp:
var input = 'subject=something1||x-access-token=something2'
var m = /subject=(.*)\|\|x-access-token=(.*)/.exec(input)
var subject = m[1]
var xAccessToken = m[2]
console.log(subject);
console.log(xAccessToken);
However, it would probably be cleaner to split it instead:
console.log('subject=something||x-access-token=something'
.split(/\|\|/)
.map(function(a) {
a = a.split(/=/);
return { key: a[0], val: a[1] }
}));

Split the date! (It's a string actually)

I want to split this kind of String :
"14:30 - 19:30" or "14:30-19:30"
inside a javascript array like ["14:30", "19:30"]
so I have my variable
var stringa = "14:30 - 19:30";
var stringes = [];
Should i do it with regular expressions? I think I need an help
You can just use str.split :
var stringa = "14:30 - 19:30";
var res = str.split("-");
If you know that the only '-' present will be the delimiter, you can start by splitting on that:
let parts = input.split('-');
If you need to get rid of whitespace surrounding that, you should trim each part:
parts = parts.map(function (it) { return it.trim(); });
To validate those parts, you can use a regex:
parts = parts.filter(function (it) { return /^\d\d:\d\d$/.test(it); });
Combined:
var input = "14:30 - 19:30";
var parts = input.split('-').map(function(it) {
return it.trim();
}).filter(function(it) {
return /^\d\d:\d\d$/.test(it);
});
document.getElementById('results').textContent = JSON.stringify(parts);
<pre id="results"></pre>
Try this :
var stringa = "14:30 - 19:30";
var stringes = stringa.split("-"); // string is "14:30-19:30" this style
or
var stringes = stringa.split(" - "); // if string is "14:30 - 19:30"; style so it includes the spaces also around '-' character.
The split function breaks the strings in sub-strings based on the location of the substring you enter inside it "-"
. the first one splits it based on location of "-" and second one includes the spaces also " - ".
*also it looks more like 24 hour clock time format than data as you mentioned in your question.
var stringa = '14:30 - 19:30';
var stringes = stringa.split("-");
.split is probably the best way to go, though you will want to prep the string first. I would go with str.replace(/\s*-\s*/g, '-').split('-'). to demonstrate:
var str = "14:30 - 19:30"
var str2 = "14:30-19:30"
console.log(str.replace(/\s*-\s*/g, '-').split('-')) //outputs ["14:30", "19:30"]
console.log(str2 .replace(/\s*-\s*/g, '-').split('-')) //outputs ["14:30", "19:30"]
Don't forget that you can pass a RegExp into str.split
'14:30 - 19:30'.split(/\s*-\s*/); // ["14:30", "19:30"]
'14:30-19:30'.split(/\s*-\s*/); // ["14:30", "19:30"]

Quick Problem - Extracting numbers from a string

I need to extract a single variable number from a string. The string always looks like this:
javascript:change(5);
with the variable being 5.
How can I isolate it? Many thanks in advance.
Here is one way, assuming the number is always surrounded by parentheses:
var str = 'javascript:change(5);';
var lastBit = str.split('(')[1];
var num = lastBit.split(')')[0];
Use regular expressions:-
var test = "javascript:change(5);"
var number = new RegExp("\\d+", "g")
var match = test.match(number);
alert(match);
A simple RegExp can solve this one:
var inputString = 'javascript:change(5);';
var results = /javascript:change\((\d+)\)/.exec(inputString);
if (results)
{
alert(results[1]); // 5
}
Using the javascript:change part in the match as well ensures that if the string isn't in the proper format, you wont get a value from the matches.
var str = 'javascript:change(5);', result = str.match(/\((\d+)\)/);
if ( result ) {
alert( result[1] )
}

Javascript extracting number from string

I have a bunch of strings extracted from html using jQuery.
They look like this:
var productBeforePrice = "DKK 399,95";
var productCurrentPrice = "DKK 299,95";
I need to extract the number values in order to calculate the price difference.
(So I wend up with ≈
var productPriceDiff = DKK 100";
or just:
var productPriceDiff = 100";)
Can anyone help me do this?
Thanks,
Jakob
First you need to convert the input prices from strings to numbers. Then subtract. And you'll have to convert the result back to "DKK ###,##" format. These two functions should help.
var priceAsFloat = function (price) {
return parseFloat(price.replace(/\./g, '').replace(/,/g,'.').replace(/[^\d\.]/g,''));
}
var formatPrice = function (price) {
return 'DKK ' + price.toString().replace(/\./g,',');
}
Then you can do this:
var productBeforePrice = "DKK 399,95";
var productCurrentPrice = "DKK 299,95";
productPriceDiff = formatPrice(priceAsFloat(productBeforePrice) - priceAsFloat(productCurrentPrice));
try:
var productCurrentPrice = productBeforePrice.replace(/[^\d.,]+/,'');
edit: this will get the price including numbers, commas, and periods. it does not verify that the number format is correct or that the numbers, periods, etc are contiguous. If you can be more precise in the exact number definitions you expcet, it would help.
try also:
var productCurrentPrice = productBeforePrice.match(/\d+(,\d+)?/)[0];
var productCurrentPrice = parseInt(productBeforePrice.replace(/[^\d\.]+/,''));
That should make productCurrentPrice the actual number you're after (if I understand your question correctly).

Categories

Resources