RegEx - prefix + input value - javascript

I have input and I would like to achieve to always have in value prefix +34 and value typed by user which consist of 9 digits
I have tried somethign like this
let val = value.replace(/[^\d]{9}/g, "+34{1}");
but it does not work, any idea what I am doing wrong ??

Simple string concatenation is enough for this.
let val = '+34' + value;
In your current code, it's actually removing entire 9 digits with the string
("+34{1}"). To refer the match in replace string you can use $& in that.
let val = value.replace(/^\d{9}/, "+34$&");
Or alternatively use positive look-ahead in the regex to assert the position where you want to insert.
let val = value.replace(/^(?=\d{9})/, "+34");

Related

how to substring in javascript but excluding symbols

I need to use (substring method) in my javascript web network project, but excluding : colon symbol, because it is hexadecimal ip address, and I don't want to accept : colons as a string or lets say number in the substring, I want to ignore it. How to do that?
This is the example IPV6 in the input field:
2001:2eb8:0dc1:54ed:0000:0000:0000:0f31
after substring from 1 to 12:
001:2eb8:0d
as you can see it accepted colons also, but in fact, I need this result:
2001:2eb8:0dc1
so by excluding these two symbols, it would have gave me that result above, but I don't know how.
and here is the code, IpAddressInput, is only a normal input field which I write the ip address in it.
Here is the code:
var IpValue = $('#IpAddressInput').val();
alert(IpValue.substr(1, (12) -1));
Answer 1: I think there is no direct function to results like you want but this answer will help you. I counted the number of colons from index 0 to 12 and then slice the source string from 0 to 12 plus the number. Here is the code:
let val = "2001:2eb8:0dc1:54ed:0000:0000:0000:0f31";
let numOfColons = val.slice(0, 12).match(/:/g).length;
let result = val.slice(0, 12 + numOfColons);
console.log(result)
Answer 2: If you are sure that there is a colon after exactly every 4 characters, a better solution will be this. The idea is to remove all colons from the string, slice from index 0 to 12, and add a colon after every 4 characters. Finally, it removes the last colon. Here is the code:
let value = "2001:2eb8:0dc1:54ed:0000:0000:0000:0f31";
let valueExcludeColon = value.replace(/:/g, ''); // '20012eb80dc154ed0000000000000f31'
let result = valueExcludeColon.slice(0,12).replace(/(.{4})/g, "$1:"); // '2001:2eb8:0dc1:'
let finalResult = result.slice(0, -1); // 2001:2eb8:0dc1
console.log(finalResult)

Split a string based on a condition

I would like to split a spreadsheet cell reference (eg, A10, AB100, ABC5) to two string parts: column reference and row reference.
A10 => A and 10
AB100 => AB and 100 ...
Does anyone know how to do this by string functions?
var res = "AA123";
//Method 1
var arr = res.match(/[a-z]+|[^a-z]+/gi);
document.write(arr[0] + "<br>" + arr[1]);
//Method 2 (as deceze suggested)
var arr = res.match(/([^\d]+)(\d+)/);
document.write("<br>" + arr[1] + "<br>" + arr[2]);
//Note here [^\d] is the same as \D
This is easiest to do with a regular expression (regex). For example:
var ref = "AA100";
var matches = ref.match(/^([a-zA-Z]+)([1-9][0-9]*)$/);
if (matches) {
var column = matches[1];
var row = Number(matches[2]);
console.log(column); // "AA"
console.log(row); // 100
} else {
throw new Error('invalid ref "' + ref + '"');
}
The important part here is the regex literal, /^([a-zA-Z]+)([1-9][0-9]*)$/. I'll walk you through it.
^ anchors the regex to the start of the string. Otherwise you might match something like "123ABC456".
[a-zA-Z]+ matches one or more character from a-z or A-Z.
[1-9][0-9]* matches exactly one character from 1-9, and then zero or more characters from 0-9. This makes sure that the number you are matching never starts with zero (i.e. "A001" is not allowed).
$ anchors the regex to the end of the string, so that you don't match something like "ABC123DEF".
The parentheses around ([a-zA-Z]+) and ([1-9][0-9]*) "capture" the strings inside them, so that we can later find them using matches[1] and matches[2].
This example is strict about only matching valid cell references. If you trust the data you receive to always be valid then you can get away with a less strict regex, but it is good practice to always validate your data anyway in case your data source changes or you use the code somewhere else.
It is also up to you to decide what you want to do if you receive invalid data. In this example I make the script throw an error, but there might be better choices in your situation (e.g. prompt the user to enter another value).

RegExp to filter characters after the last dot

For example, I have a string "esolri.gbn43sh.earbnf", and I want to remove every character after the last dot(i.e. "esolri.gbn43sh"). How can I do so with regular expression?
I could of course use non-RegExp way to do it, for example:
"esolri.gbn43sh.earbnf".slice("esolri.gbn43sh.earbnf".lastIndexOf(".")+1);
But I want a regular expression.
I tried /\..*?/, but that remove the first dot instead.
I am using Javascript. Any help is much appreciated.
I would use standard js rather than regex for this one, as it will be easier for others to understand your code
var str = 'esolri.gbn43sh.earbnf'
console.log(
str.slice(str.lastIndexOf('.') + 1)
)
Pattern Matching
Match a dot followed by non-dots until the end of string
let re = /\.[^.]*$/;
Use this with String.prototype.replace to achieve the desired output
'foo.bar.baz'.replace(re, ''); // 'foo.bar'
Other choices
You may find it is more efficient to do a simple substring search for the last . and then use a string slicing method on this index.
let str = 'foo.bar.baz',
i = str.lastIndexOf('.');
if (i !== -1) // i = -1 means no match
str = str.slice(0, i); // "foo.bar"

How do I check if a string is of the form 10*10*10 using Javascript/JQuery and then do math

I'm trying to dynamically calculate volume based on the input of some carton dimensions.
e.g a For a carton with dimensions 10cm x 10cm x 10cm the user inputs 10*10*10 into a text input.
My javascript will then check to see if the input matches this pattern and do the math and populate another input with the result. 10 x 10 x 10 = 1000.
I think I need to use Regular Expressions which I don't have much experience with. The code below stops working at the match stage.(Invalid regular expression: /d+*d+*d+/: Nothing to repeat) Although I'm pretty sure I don't know what I'm doing after that.
Can anyone help?
carton_dimensions=$(this).val();
var pattern = "(\d+)\*(\d+)\*(\d+)";
var result = carton_dimensions.match(pattern);
if(result){
volume=result[0]*result[1]*result[2];
}
"(\d+)\*(\d+)\*(\d+)"
^ ^
is a string literal. What you need is a regex literal:
/(\d+)\*(\d+)\*(\d+)/
^ ^
Alternatively you can use the RegExp constructor, but then you have to deal with escaping special characters within the string literal so the value is equivalent to the regular expression that you intend to use:
new RegExp("(\\d+)\\*(\\d+)\\*(\\d+)")
First, the pattern is worngly declared, it should be without " but /:
var pattern = /(\d+)\*(\d+)\*(\d+)/;
Also, the results you are looking for are in the indexes 1,2 and 3:
volume = result[1] * result[2] * result[3];
So, your final code must something like this:
carton_dimensions = $("input").val();
var pattern = /(\d+)\*(\d+)\*(\d+)/;
var result = carton_dimensions.match(pattern);
if(result){
volume = result[1] * result[2] * result[3];
}
Here is a JSFiddle with a working example.
For the calculation, you can use javascript's eval like this:
var answer = eval(result[0] + '*' + result[1] + '*' + result[2]);
And since you are validating the input, you should be safe.

regex - get numbers after certain character string

I have a text string that can be any number of characters that I would like to attach an order number to the end. Then I can pluck off the order number when I need to use it again. Since there's a possibility that the number is variable length, I would like to do a regular expression that catch's everything after the = sign in the string ?order_num=
So the whole string would be
"aijfoi aodsifj adofija afdoiajd?order_num=3216545"
I've tried to use the online regular expression generator but with no luck. Can someone please help me with extracting the number on the end and putting them into a variable and something to put what comes before the ?order_num=203823 into its own variable.
I'll post some attempts of my own, but I foresee failure and confusion.
var s = "aijfoi aodsifj adofija afdoiajd?order_num=3216545";
var m = s.match(/([^\?]*)\?order_num=(\d*)/);
var num = m[2], rest = m[1];
But remember that regular expressions are slow. Use indexOf and substring/slice when you can. For example:
var p = s.indexOf("?");
var num = s.substring(p + "?order_num=".length), rest = s.substring(0, p);
I see no need for regex for this:
var str="aijfoi aodsifj adofija afdoiajd?order_num=3216545";
var n=str.split("?");
n will then be an array, where index 0 is before the ? and index 1 is after.
Another example:
var str="aijfoi aodsifj adofija afdoiajd?order_num=3216545";
var n=str.split("?order_num=");
Will give you the result:
n[0] = aijfoi aodsifj adofija afdoiajd and
n[1] = 3216545
You can substring from the first instance of ? onward, and then regex to get rid of most of the complexities in the expression, and improve performance (which is probably negligible anyway and not something to worry about unless you are doing this over thousands of iterations). in addition, this will match order_num= at any point within the querystring, not necessarily just at the very end of the querystring.
var match = s.substr(s.indexOf('?')).match(/order_num=(\d+)/);
if (match) {
alert(match[1]);
}

Categories

Resources