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)
Related
I have the below string in Javascript
var str = "β{;{9}/{(n-7)(n-8)}} ≤ β{;{18({3}/{2})}/{(n-8) 8} ≥ ;{36}/{9.8} ;{9}/{4}}";
I need to extract the text between curly braces starts with β symbol
i.e. β{text inside curly brases with {nested}}.
So from the above str I need to extract below two values based on β{ inside everything}
str1 = ";{9}/{(n-7)(n-8)}"`
str2 = ";{18({3}/{2})}/{(n-8) 8} ≥ ;{36}/{9.8} ;{9}/{4}"
I tried many regex examples the closest I found working is a PHP example from this stackover flow link, but its not working in Javascript.
Please help me as pattern is having PHP syntax which is failing in Javascript
\{((?:[^{}]++|\{(?1)\})++)\}
Example 1 :
testinput = "β{test{test{12351}}{a+b}{1/2}}" // Input
testoutput = "{test{test{12351}}{a+b}{1/2}}β"; // output
Example 2:
testinput = "β{test}" // Input
testoutput = "{test}β"; // output
As JavaScript has no support for recursion in regex, the (?1) part of the regex is not valid (nor the double plus, but that is unrelated).
What you can do is first count the number of opening braces in the input, which gives you a ceiling on the nesting depth. Then construct a regex dynamically that supports that depth of nesting:
function extract(str) {
const count = str.match(/(?<!β){/g)?.length ?? 0;
const regex = RegExp("(?<=β{)[^{}]*" + "({[^{}]*".repeat(count) + "}[^{}]*)*".repeat(count) + "(?=})", "g");
return str.match(regex);
}
var str = "β{;{9}/{(n-7)(n-8)}} ≤ β{;{18({3}/{2})}/{(n-8) 8} ≥ ;{36}/{9.8} ;{9}/{4}}";
var parts = extract(str);
console.log(parts);
Does anyone know how to make a number from a string with comma separators, in JS.
I got: "23,21" and I want to get it as a number value.
"23,21" --> 23,21
You can use https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseFloat
But before you need to replace comma for dot.
parseFloat('23,21'.replace(/,/, '.')); // == 23.21
let x = '16,5';
parseFloat(x.replace(/,/, '.')); // == 16.5
You can but not with the "comma" (,). In some countries people do use commas instead of dots to write decimals. If that's the case then what you can do is:
let a = "23,25";
let b = a.replaceAll(',', '.');
console.log(parseFloat(b));
But doing the this with the comma is also not wrong. But you will only get the part before the decimal.
i.e. 23 in your case
Check if you want this.
var str = '23,21';
console.log((str.split(",").map((i) => Number(i))));
UPDATE
var str = '23,21';
var arr = str.split(",").map((i) => Number(i));
console.log(parseFloat(arr.join('.')));
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]);
I have a two different different numbers, each with a dollar sign. I want to get the two numbers separately.
JavaScript:
function price_range(id){
//var str = $('#'+id).val();
var str = '$75 - $300';
var removeDollar = str.replace(/\$/,'');
alert(removeDollar);
}
Click Here
The above code only replaces the first dollar sign, but I have two dollar signs with number. How can I get 75 and 300 separately?
You can just get all the numbers from the string, like this
console.log('$75 - $300'.match(/(\d+)/g));
# [ '75', '300' ]
Note: This simple RegEx will match and get all the numbers, even if there are more than 2 numbers in the string. But for this simple task, you don't need a complicate RegEx.
If you want to fix your program, you can do it like this
console.log('$75 - $300'.replace(/\$/g, '').split(/\s*-\s*/));
# [ '75', '300' ]
replace(/\$/g, '') will replace $ symbol from the string and then you can split the string based on \s*-\s*, which means zero or more white space characters, followed by -, and followed by zero or more white space characters.
You could extend the regular expression in the .replace() function to have a global flag g:
str.replace(/\$/g,'');
The whole script would work like this, but will be specific to removing the $ sign.
function price_range(id){
//var str = $('#'+id).val();
var str = '$75 - $300';
var removeDollar = str.replace(/\$/g,'');
alert(removeDollar);
}
Click Here
An option would be to extract numbers with a regular expression like this:
var str = '$70 - $300 some other 500%';
var arrOfStrings = str.match(/\d+/gi);
// arrOfStrings = ['70', '300', '500']
var arrOfNrs = arrOfStrings.map(function (e) {
return parseInt(e);
}); // map not supported by all browsers. you can use the _.map from underscorejs.org
// arrOfNrs = [70, 300, 500]
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.