I'm quite new to JavaScript, so the code below can be pretty bad. I'm just trying to extract a value from a string. I know parseFloat() would probably not be the solution, but is there any function that would allow for that?
p id="1" would contain some random text and end with a value.
Here below my example:
<div id="abc">
<p id="1">abc 0.99</p>
<p id="2">-</p>
<button onclick="GetValue()">Extract value</button>
</div>
<script>
function GetValue() {
var Value = parseFloat(document.getElementById("1").innerHTML);
document.getElementById("2").innerHTML = Value;
}
</script>
Any suggestion is much appreciated!
The suggestion from this other thread JavaScript get number from string worked, thanks for pointing that out!
Updated code:
<div id="abc">
<p id="1">abc 0.99</p>
<p id="2">-</p>
<button onclick="GetValue()">Extract value</button>
</div>
<script>
function GetValue() {
var String = document.getElementById("1").innerHTML;
var Value = String.replace( /^\D+/g, '');
document.getElementById("2").innerHTML = Value;
/*
Solution 2> var Value = String.replace(/^.*?(-?([0-9]+|[0-9]*[.][0-9]+))[ \t]*$/gi,'$1');
Solution 3> var Value = String.match(/\d+(\.\d+)?/)[0];
*/
}
</script>
You can use following regex:
var str = "abc 0.99";
let number=str.match(/\d+(\.\d+)?/)[0];
alert(number);
Regex Explanation
0-9 : Matches any number
. : Matches . literal
+ : Matches previous group one or more time
When the structure of your string is always like "textspacenumber" where number is always at the end, you could just split the string and use the last item:
const str = "abc 0.99";
const tokens = str.split( ' ' );
const number = parseFloat( tokens[ tokens.length - 1 ] );
console.log( number );
This is way simpler than using RegEx (which is fine too, but slower)
parseFloat is fine, if you really need the numerical value. The "some random text and end with a value" part can be a bit tricker, depending on what that text can be. (for example can it contain other numbers?)
Here's a way to do it with regular expressions:
var s = document.getElementById('1').innerHTML;
s = s.replace(/^.*?(-?([0-9]+|[0-9]*[.][0-9]+))[ \t]*$/gi,'$1');
var x = parseFloat(s);
document.getElementById('2').innerHTML = x;
Explanation of the 2nd line: this is a regular expression that extracts a numerical part from the end of a string. A 'numerical part' here may start with a minus sign (for negative numbers), and then either just a bunch of digits (for integer values), or zero or more digits followed by a decimal point followed by one or more decimals. I've added [ \t]* to also allow for some optional whitespace at the end.
This can look pretty crazy if you're not familiar with regular expressions.
By the way, since you're only putting the result back into your HTML content, there is actually no need for parseFloat. You can just put the resulting s (which is still a string but only the number, with the content before number stripped away) straight back into the HTML.
If you are doing actual calculations with the number, then yes, use parseFloat(s).
Try this:
function GetValue() {
var myValue = document.getElementById("1").textContent;
document.getElementById("2").innerHTML = myValue;
}
Note: You were trying to assign value to a system variable - Value.
Code runing: https://jsfiddle.net/2ohf65hc/
Related
I'm working with a string "(20)". I need to convert it to an int. I read parseInt is a function which helps me to achieve that, but i don't know how.
Use string slicing and parseInt()
var str = "(20)"
str = str.slice(1, -1) // remove parenthesis
var integer = parseInt(str) // make it an integer
console.log(integer) // 20
One Line version
var integer = parseInt("(20)".slice(1, -1))
The slice method slices the string by the start and end index, start is 1, because that’s the (, end is -1, which means the last one - ), therefore the () will be stripped. Then parseInt() turns it into an integer.
Or use regex so it can work with other cases, credits to #adeithe
var integer = parseInt("(20)".match(/\d+/g))
It will match the digits and make it an integer
Read more:
slicing strings
regex
You can use regex to achieve this
var str = "(20)"
parseInt(str.match(/\d+/g).join())
Easy, use this
var number = parseInt((string).substr(2,3));
You need to extract that number first, you can use the match method and a regex \d wich means "digits". Then you can parse that number
let str = "(20)";
console.log(parseInt(str.match(/\d+/)));
Cleaner version of Hedy's
var str = "(20)";
var str_as_integer = parseInt(str.slice(1, -1))
I have a number returned from the database
e.g.
329193914
What I would like to do it simply be able to just insert dashes every 3 characters.
e.g.
329-193-914
I was looking at regex, replace and slice , slice I had a hard time with as a lot of example are like f.value and i'm not passing in "this" (entire element)
if your number can be treated as a string:
var str = '329193914';
var arr = str.match(/.{3}/g); // => ['329', '193', '914']
var str2 = arr.join('-'); // => '329-193-914'
I have function that is supposed to "clean" a string and i'd like to use replace() to do that, but I can't figure out why the following code is not working when the text comes from an input[text].
for instance :
console.log(getCleanText("ééé")); // works fine, it displays : eee
but
// my_id is an input with type="text"
var my_text = document.getElementById("my_id").value
console.log(getCleanText(my_text)); // doesn't work at all, it displays : ééé
the function code is :
function getCleanText(some_text) {
var clean_text = some_text.toLowerCase();
clean_text = clean_text.replace("é", "e");
clean_text = clean_text.split("é").join("e"); // give it another try
return clean_text;
}
any idea ?
I'm willing to bet your problem lies in a misunderstanding of Unicode.
é
é
Those two characters above are two different characters. The first is the letter e, with an accent character (U+0301). The other is a single character, U+00E9.
You need to ensure you're replacing both versions.
I think the character "é" from element value is the different from the "é" constant. To resolve that you can take look at the int value of the input.
var inputEValue = document.getElementById("my_id").charCodeAt(0);
var constantEValue = "é".charCodeAt(0);
Then you will be able to detect what characters you are replacing.
If you want to just remove accents from text, take look at the question Remove accents/diacritics in a string in JavaScript
Try this:
function getCleanText(old_string)
{
var new_string = old_string.toLowerCase();
return new_string.replace(/é/g, 'e');
}
Ed: beaten by the Robert. For reference, see here: What are useful JavaScript methods that extends built-in objects?
Try this:
function cleanText(text) {
var re = new RegExp(/\u0301|\u00e9/g);
return text.replace(re, "e").toLowerCase();
}
cleanText("éééé")
--
Updated to use the proposed UniCode chars by Matt Grande
What is the output of
var my_text = document.getElementById("my_id").value; ?
Depending on your html, you might need to use other functions to get the data. e.g
var my_text = document.getElementById("my_id").innerHTML;
http://jsbin.com/obAmiPe/5/edit?html,js,console,output
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.
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.