find a specific number in a string - javascript

I have this variable x, that contains this string:
var x="Math.pow(5,3)";
How can I find the exponent(in this case 3), considering that my "Math.pow" string may contain any number as its base and exponent.
I was thinking to combine somehow the RegEx with theNumber() function, but no result came up.

You can use regex and search for the digits between , and ):
var x = "Math.pow(5,3)";
var reg = /,(\d+)\)/;
console.log(x.match(reg)[1]);
Or a bit shorter, just search for digits after ,:
var x = "Math.pow(5,34)";
var reg = /,(\d+)/;
console.log(x.match(reg)[1]);

Related

How to move each character in a TextArea with ES6?

I need to go through a textarea to find and separate certain strings, such as:
Example 1) Separate the numbers from the text.
String "KAEeqk41KK EeqkKEKQ3 EKEK 43" - Result: [41, 3, 43]
Example 2) Count the blanks in the String.
OBS: _ = blank space
String "KAkeaekaek _ kea41 __ 3k1k31"
You could separate the numbers using match() and count some match using length, I'm not sure what do you mean with blanks but this example could be useful.
//var str = document.getElementById("textarea").value;//<-- probably somethig like this
var str = "KAEeqk41KK EeqkKEKQ3 EKEK 43";
var str2 = "KAkeaekaek _ kea41 __ 3k1k31"
var numbers = str.match(/[0-9]+/g)
var blanks = str2.match(/_| /g).length//<-- count spaces and _
console.log(numbers)
console.log(blanks)

How to extract a rational number between a parenthesis and letters using regex?

I'm trying to extract the degree rate from the CSS transform property,
transform = "rotate(33.8753deg) translateZ(0px)"
with a regular expression. So far I've succeeded to get almost the exact number:
const re = new RegExp('.*rotate( *(.*?) *deg).*', 'm');
let degRate = transform.match(re);
Output: An array which the third element is:
"(33.8753"
How can I get only the number without the parenthesis?
How can I get only the number? (not in an array)
You can use the RegEx \(([^(]*)deg\) and get the first group with .match(...)[1]
\( matches the first (
([^(]*) captures anything but ( 0 or more times
deg\) matches deg) literally.
let str = "rotate(33.8753deg) translateZ(0px)";
let deg = str.match(/\(([^(]*)deg\)/)[1];
console.log(deg);
Simpler extraction:
let str = "rotate(33.8753deg) translateZ(0px)";
let deg = parseFloat(str.replace(/^.*rotate\(/,""));
console.log(deg);

Parsing a String looking characters

I am trying to extract the numbers of this string: "ax(341);ay(20);az(3131);"
I think that I can do it how this:
var ax = data.split('(');
var ax2 = ax[1].split(')');
ax2[0] has "341"
Now If I can repeat this but starting in the next indexOf to take the second number.
I think that it's a bad practice, so I ask you If you have a better idea.
Thanks in advance
Use a regular expression:
var str = "ax(-341);ay(20);az(3131);"
var regex = /(-?\d+)/g
var match = str.match(regex);
console.log(match); // ["-341", "20", "3131"]
Now you can just access the numbers in the array as normal.
DEMO
You can use regex to extract all numbers from this.
var data = "ax(341);ay(20);az(3131);";
var ax = data.match(/\d+/g);
Here ax is now ["341", "20", "3131"]
Note that ax contains numbers as string. To convert them to number, use following
ax2 = ax.map( function(x){ return parseInt(x); } )
EDIT: You can alternatively use Number as function to map in the line above. It'll look like,
ax2 = ax.map( Number )
After this ax2 contains all the integers in the original string.
You could use a regular expression, eg:
var string = 'ax(341);ay(20);az(3131);';
var pattern = /([0-9]{1,})/g;
var result = string.match(pattern);
console.log(result);
// ["341", "20", "3131"]
http://regex101.com/r/zE9pS7/1

split string based on a symbol

I'm trying to split a string into an array based on the second occurrence of the symbol _
var string = "this_is_my_string";
I want to split the string after the second underscore. The string is not always the same but it always has 2 or more underscores in it. I always need it split on the second underscore.
In the example string above I would need it to be split like this.
var split = [this_is, _my_string];
var string = "this_is_my_string";
var firstUnderscore = string.indexOf('_');
var secondUnderscore = string.indexOf('_', firstUnderscore + 1);
var split = [string.substring(0, secondUnderscore),
string.substring(secondUnderscore)];
Paste it into your browser's console to try it out. No need for a jsFiddle.
var string = "this_is_my_string";
var splitChar = string.indexOf('_', string.indexOf('_') + 1);
var result = [string.substring(0, splitChar),
string.substring(splitChar, string.length)];
This should work.
var str = "this_is_my_string";
var matches = str.match(/(.*?_.*?)(_.*)/); // MAGIC HAPPENS HERE
var firstPart = matches[1]; // this_is
var secondPart = matches[2]; // _my_string
This uses regular expressions to find the first two underscores, and captures the part up to it and the part after it. The first subexpression, (.*?_.*?), says "any number of characters, an underscore, and again any number of characters, keeping the number of characters matched as small as possible, and capture it". The second one, (_.*) means "match an underscore, then any number of characters, as much of them as possible, and capture it". The result of the match function is an array starting with the full matched region, followed by the two captured groups.
I know this post is quite old... but couldn't help but notice that no one provided a working solution. Here's one that works:
String str = "this_is_my_string";
String undScore1 = str.split("_")[0];
String undScore2 = str.split("_")[1];
String bothUndScores = undScore1 + "_" + undScore2 + "_";
String allElse = str.split(bothUndScores)[1];
System.out.println(allElse);
This is assuming you know there will always be at least 2 underscores - "allElse" returns everything after the second occurrence.

Javascript / Jquery - Get number from string

the string looks like this
"blabla blabla-5 amount-10 blabla direction-left"
How can I get the number just after "amount-", and the text just after "direction-" ?
This will get all the numbers separated by coma:
var str = "10 is smaller than 11 but greater then 9";
var pattern = /[0-9]+/g;
var matches = str.match(pattern);
After execution, the string matches will have values "10,11,9"
If You are just looking for thew first occurrence, the pattern will be /[0-9]+/ - which will return 10
(There is no need for JQuery)
This uses regular expressions and the exec method:
var s = "blabla blabla-5 amount-10 blabla direction-left";
var amount = parseInt(/amount-(\d+)/.exec(s)[1], 10);
var direction = /direction-([^\s]+)/.exec(s)[1];
The code will cause an error if the amount or direction is missing; if this is possible, check if the result of exec is non-null before indexing into the array that should be returned.
You can use regexp as explained by w3schools. Hint:
str = "blabla blabla-5 amount-10 blabla direction-left"
alert(str.match(/amount-([0-9]+)/));
Otherwize you can simply want all numbers so use the pattern [0-9]+ only.
str.match would return an array.

Categories