Only extract digits with javascript - javascript

I need to extract digits only (at least 2 but not more than 3) from an option text in a drop down list and get that shown in an input field. I've read about regexp (http://www.javascriptkit.com/jsref/regexp.shtml) and thought i had it all figured out. But i just can't seem to get it to work.
<script>
function copyEbc() {
var a = document.getElementById("malt"); // the <select>
var onlydig = /\d{1,3}/ // regexp
var option = a.options[a.selectedIndex].text(onlydig); // regexp on options
var txt = document.getElementById("ebc").value;
txt = txt + option;
document.getElementById("ebc").value = txt;
}
</script>
Example, I only want "4" from a selected option with the text "Pilsner 4 EBC".
Am I completely lost here?
Input much appreciated, cheers

You're trying to call the text value as a function (your JS console has probably complained about this).
Match against the regular expression, instead. match[0] will contain the matched text:
var option = a.options[a.selectedIndex].text.match(onlydig)[0];

to simply extract the number(s) from a string use match:
var numberPattern = /\d+/g;
var foo = 'Pilsner 4 EBC';
var numbers = foo.match(numberPattern);
alert(numbers); // alerts the array of numbers

You need to use the "match" method of the regexp object. AFAIK the "text" method you are using do not exist.

Related

javascript regular expression - getting value after colon, without the colon

I have tried the https://www.regex101.com/#javascript tool, as well as a similar stackoverflow question and yet haven't been able to solve/understand this. Hopefully someone here can explain what I am doing wrong. I have created as detailed, step-by-step of an example as I can.
My goal is to be able to parse custom attributes, so for example:
I wrote some jquery code to pull in the attribute and the value, and then wanted to run regex against the result.
Below is the html/js, the output screenshot, and the regular expression screenshot, which says my regex query should match what I am expecting.
Expected result: 'valOne'
Result: ':valOne' <-- why am I getting a ':' character?
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('[customAttr]').each(function(){
var attrValues = $(this).attr('customAttr');
var regEx_attrVal = /[\w:]+?(?=;|$)/g;
var regEx_preColon = /[\w]+?(?=:)/g;
var regEx_postColon = /:(\w*)+?(?=;|\b)/g;
var customAttrVal = attrValues.match(regEx_attrVal);
var customAttrVal_string = customAttrVal.toString();
console.log('customAttrVal:');
console.log(customAttrVal);
console.log('customAttrVal_string: '+customAttrVal_string);
var preColon = customAttrVal_string.match(regEx_preColon);
preColon_string =preColon.toString();
console.log('preColon');
console.log(preColon);
console.log('preColon_string: '+preColon_string);
var postColon = customAttrVal_string.match(regEx_postColon);
postColon_string = postColon.toString();
console.log('postColon');
console.log(postColon);
console.log('postColon_string: '+postColon_string);
console.log('pre: '+preColon_string);
console.log('post: '+postColon_string);
});
});
</script>
</head>
<body>
<div customAttr="val1:valOne">
Test custom attr
</div>
</body>
</html>
When you use String#match() with a regex with a global modifier, all the capture groups (those strings in the regex101.com right-hand bottom 'MATCH INFORMATION' pane are the values captured into Groups with ID 1 and higher) defined in the pattern are lost, and you only get an array of matched values.
You need to remove /g from your regexps and fix them as follows:
var regEx_attrVal = /[\w:]+(?=;|$)/;
var regEx_preColon = /\w+(?=:)/;
var regEx_postColon = /:(\w+)(?=;|\b)/;
Then, when getting the regEx_postColon captured value, use
var postColon = customAttrVal_string.match(regEx_postColon);
var postColon_string = postColon !== null ? postColon[1] : "";
First, check if there is a postColon regex match, then access the captured value with postColon[1].
See the whole updated code:
$(document).ready(function() {
$('[customAttr]').each(function() {
var attrValues = $(this).attr('customAttr');
var regEx_attrVal = /[\w:]+(?=;|$)/;
var regEx_preColon = /\w+(?=:)/;
var regEx_postColon = /:(\w+)(?=;|\b)/;
var customAttrVal = attrValues.match(regEx_attrVal);
var customAttrVal_string = customAttrVal.toString();
console.log('customAttrVal:');
console.log(customAttrVal);
console.log('customAttrVal_string: ' + customAttrVal_string);
var preColon = customAttrVal_string.match(regEx_preColon);
preColon_string = preColon.toString();
console.log('preColon');
console.log(preColon);
console.log('preColon_string: ' + preColon_string);
var postColon = customAttrVal_string.match(regEx_postColon);
var postColon_string = postColon !== null ? postColon[1] : "";
console.log('postColon');
console.log(postColon);
console.log('postColon_string: ' + postColon_string);
console.log('pre: ' + preColon_string);
console.log('post: ' + postColon_string);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div customAttr="val1:valOne">
Test custom attr
</div>
I haven't trudged through all the code, but something you need to understand about regexes is the difference between $0 and $1.
$0 is highlighted in blue. That is the entire part the regex matched.
You want $1. That's where the matches captured by the parenthesis are.
Read more about capture groups here.
var match = myRegexp.exec(myString);
alert(match[1]); // This accesses $1
use data attributes. you can store json strings in them and access them like objects.
HTML
<div id='div' data-custom='{"val1":"valOne","a":"b"}'></div>
jQ
$("#div").data("custom").val1; //valOne
$("#div").data("custom").a; //b
I guess this is the regex pattern that you're looking for:
(?!(.*?):).*
Explanation
(.*?:) Select all type of values and any number of times and a match that contains (:) simbol
(?! :) select inverse values of the first pattern, its kinda negation
( ).* Select all type of values after the evaluations
Also you can do the same with Jquery substring which for me the most simple way to do it, just like this:
How to substring in jquery

How To Remove All Text Before a Specific Value in a String

I have the following string, "blahblahhellothere", that I would like to be shortened to "hellothere" using JavaScript and/or JQuery.
I have tried using the following code:
var titletext123 = "blahblah<br>hellothere"
var injuryt3xt = titletext123.substring(titletext123.indexOf("<br>") +1);
Which only returns "br>hellothere".
Does anyone have any code which will get rid of the and all text before it?
Thank you very much. All of your help is appreciated!
Make it
var titletext123 = "blahblah<br>hellothere" var injuryt3xt = titletext123.substring(titletext123.indexOf("<br>") + 4);
So it is +4. Which accounts for all the characters in <br>.
You can use split() and get second element.
var titletext123 = "blahblah<br>hellothere" ;
var injuryt3xt = titletext123.split("<br>")[1];
alert(injuryt3xt);
Using regular expression:
var text = "blahblah<br>hellothere"
var clipped = str.replace(/.+\<br\>/, ""));
Another option (depending on circumstances) might be:
var injuryt3xt = titletext123.split("<br>")[1];
Which would split the string on <br> and return an array with the left-over parts ... the second of which is referred to with the [1]

Trim a variable's value until it reaches to a certain character

so my idea is like this..
var songList = ["1. somesong.mid","13. abcdef.mid","153. acde.mid"];
var newString = myString.substr(4); // i want this to dynamically trim the numbers till it has reached the .
// but i wanted the 1. 13. 153. and so on removed.
// i have more value's in my array with different 'numbers' in the beginning
so im having trouble with this can anyone help me find a more simple solution which dynamically chop's down the first character's till the '.' ?
You can do something like
var songList = ["1. somesong.mid","13. abcdef.mid","153. acde.mid"];
songList.forEach(function(value, i){
songList[i] = value.replace(/\d+\./, ''); //value.substr(value.indexOf('.') + 1)
});
Demo: Fiddle
You can use the string .match() method to extract the part up to and including the first . as follows:
var newString = myString.match(/[^.]*./)[0];
That assumes that there will be a match. If you need to allow for no match occurring then perhaps:
var newString = (myString.match(/[^.]*./) || [myString])[0];
If you're saying you want to remove the numbers and keep the rest of the string, then a simple .replace() will do it:
var newString = myString.replace(/^[^.]*. */, "");

Populating div with the last three characters from a form input text element?

I have this code that populates the div with the form input data:
var div = $('div')[0];
$('input').bind('keyup change', function() {
div.innerHTML = this.value;
});
but I only want to extract the three last characters from the input field not all characters. How can I make this happen using jQuery?
Thanx!
You can use JavaScripts build-in method .substr() for that:
var div = $('div')[0];
$('input').bind('keyup change', function() {
var val = this.value,
valLength = val.length;
div.innerHTML = valLength < 3 ? val : val.substr(valLength - 3, 3);
// check if the value has less than three chracters. If yes return the plain value, if not return the less three characters.
});
.substr() cuts out a part of the string. It accepts two arguments. The first one determinates at what position you want the substring to begin and the second one says how long it should be.
var str =this.value;
div.innerHTML = str.substring(str.length-3,str.length);
Here is jsFiddle
In this case, I would use slice():
div.innerHTML = this.value.slice(-3);
slice() takes two arguments; the begin index and the end index. If either is negative, the index is takes as an offset from the end of the string.
var txt = "string";
txt = txt.substring(txt.length-3);
http://jsfiddle.net/WyT5j/
You can use substr on value as follows:
div.innerHTML = this.value.substr(-3);
Although as Microsoft JScript doesn't support a negative start value, you may prefer:
div.innerHTML = this.value.substr(this.value.length-3);
One additional note, I would never use 'innerHTML' with a user input value... it gives needlessly elevated access to the target element in your case. Instead (as you're using jQuery), use:
div.text(this.value.substr(-3));

selecting second string point using js substring

i want to select a sting from the long para. it has number of dot('.')s. i want to trim the word from the second one, is it any way to do this?
example
var name = "one.two.three";
name.substring(0,name.indexOf('.'))
name.substring(0,name.lastIndexOf('.'))
from above trimming in case if i use indexOf it gives first word (one), if i use lastIndex of it gives the word (three), but i need to select the second one, to get value as 'second'
how can i trim this using indexOf method? or to select multicombination strings like one.three or one.two, or two.three?
thanks in advance!
use string.split.
e.g.
name.split(".")[1]
var name="one.two.three";
var result=name.split(".").slice(0,2).join(".");
Example:
"".split(".").slice(0,2).join(".") // return ""
"one".split(".").slice(0,2).join(".") // return "one"
"one.two".split(".").slice(0,2).join(".") // return "one.two"
"one.two.three".split(".").slice(0,2).join(".") // return "one.two"
"one.two.three.four.five".split(".").slice(0,2).join(".") // return "one.two"
Is that work for you ?
var name = "one.two.three";
var params = name.split('.');
console.log(params[1]);
use Split
var name = "one.two.three";
var output = name.split('.');
alert(output[1]);
example here

Categories

Resources