I want to find a string in style of '/89/'
Let's say I have this string: '78/12/98 something else' and want to transform it into 'something else'.
And let's assume that not every string has to contain this type of expression(if the search function returns -1 we do nothing).
How to do this?
let string = '78/12/98 something else';
let index = string.search(look for description);
if(index!=-1){
string = string.substring(index+5);
}
console.log(string);
// OUTPUT: 'something else'
let string2 ='no double backslashes with digits between them';
index = string.search(look for description);
if(index!=-1){
string = string.substring(index+5);
}
console.log(string2);
// OUTPUT: 'no double backslashes with digits between them';
The pattern you are looking for is
Two digits / Two digits / Two digits space anything endline
\d\d/\d\d/\d\d\s(.*$)
or maybe
Zero or Two digits / Zero or Two digits / Zero or Two digits space anything endline
\d{0,2}/\d{0,2}/\d{0,2}\s(.*$)
replace with
\1 It will replace with anything it matched inside ().
For JS you can do as follow
let string = '78/12/98 something else';
let patt = /\d{0,2}\/\d{0,2}\/\d{0,2}\s/; // Creates a regex patern
string = string.replace(patt, ''); // replace finds with ''
enter image description here
Related
string = '1,23'
When a comma is present in the string, I want the regex to match the first digit (\n) after the comma e.g.2.
Sometimes the comma will not be there. When it's not present, I want the regex to match the first digit of the string e.g. 1.
Also, we can't reverse the order of the string to solve this task.
I am genuinely stuck. The only idea I had was prepending this: [,|nothing]. I tried '' to mean nothing but that didn't work.
You can match an optional sequence of chars other than a comma and then a comma at the start of a string, and then match and capture the digit with
/^(?:[^,]*,)?(\d)/
See the regex demo.
Details
^ - start of string
(?:[^,]*,)? - an optional sequence of
[^,]* - 0 any chars other than a comma
, - a comma
(\d) - Capturing group 1: any digit
See the JavaScript demo:
const strs = ['123', '1,23'];
const rx = /^(?:[^,]*,)?(\d)/;
for (const s of strs) {
const result = (s.match(rx) || ['',''])[1];
// Or, const result = s.match(rx)?.[1] || "";
console.log(s, '=>', result);
}
I have a text string that can be as follows let str = '10x2.34' from which I would like to get only the numbers so try the following:
str.match(/\d+/g)
This ignores the characters and returns the numbers to me, but it only works for whole numbers, so how could I get the whole numbers and decimals, which can come in the following ways: let str = '10x2.34' or let str = '10x2,34'
Match digits with \d and punctuation with \. or , :
str.match(/[\d\.,]+/g)
const regex = /[\d\.,]+/g
console.log( "10x2.34".match(regex) ) // ["10","2.34"]
console.log( "10x2,34".match(regex) ) // ["10","2,34"]
I'm working with a string where I need to extract the first n characters up to where numbers begin. What would be the best way to do this as sometimes the string starts with a number: 7EUSA8889er898 I would need to extract 7EUSA But other string examples would be SWFX74849948, I would need to extract SWFX from that string.
Not sure how to do this with regex my limited knowledge is blocking me at this point:
^(\w{4}) that just gets me the first four characters but I don't really have a stopping point as sometimes the string could be somelongstring292894830982 which would require me to get somelongstring
Using \w will match a word character which includes characters and digits and an underscore.
You could match an optional digit [0-9]? from the start of the string ^and then match 1+ times A-Za-z
^[0-9]?[A-Za-z]+
Regex demo
const regex = /^[0-9]?[A-Za-z]+/;
[
"7EUSA8889er898",
"somelongstring292894830982",
"SWFX74849948"
].forEach(s => console.log(s.match(regex)[0]));
Can use this regex code:
(^\d+?[a-zA-Z]+)|(^\d+|[a-zA-Z]+)
I try with exmaple and good worked:
1- somelongstring292894830982 -> somelongstring
2- 7sdfsdf5456 -> 7sdfsdf
3- 875werwer54556 -> 875werwer
If you want to create function where the RegExp is parametrized by n parameter, this would be
function getStr(str,n) {
var pattern = "\\d?\\w{0,"+n+"}";
var reg = new RegExp(pattern);
var result = reg.exec(str);
if(result[0]) return result[0].substr(0,n);
}
There are answers to this but here is another way to do it.
var string1 = '7EUSA8889er898';
var string2 = 'SWFX74849948';
var Extract = function (args) {
var C = args.split(''); // Split string in array
var NI = []; // Store indexes of all numbers
// Loop through list -> if char is a number add its index
C.map(function (I) { return /^\d+$/.test(I) === true ? NI.push(C.indexOf(I)) : ''; });
// Get the items between the first and second occurence of a number
return C.slice(NI[0] === 0 ? NI[0] + 1 : 0, NI[1]).join('');
};
console.log(Extract(string1));
console.log(Extract(string2));
Output
EUSA
SWFX7
Since it's hard to tell what you are trying to match, I'd go with a general regex
^\d?\D+(?=\d)
I see somebody already asked this question but the result is not really in the case of number is decimal digit.
Example:
var str = "textsometext13.523 after text";
Then if I use str.replace(/[^0-9]/gi, '');
It will return 13523 instead of 13.523
How I can use new regex to get it?
Thank you very much.
If you know your input string will only contain one number and not have a full stop at the end then simply update your regex to include a . in the list of characters to keep:
/[^0-9.]/gi
But if you need to allow for input like the following:
"text 123.12 text 13"
"The numbers are 132.12, 144.11, and 123.1."
...then you should use the .match() method, which with the right regex will return an array of matched numbers (or return null if there were no matches):
var results = input.match(/\d+(?:\.\d+)?/g);
That is, match one or more digits \d+, that are optionally followed by a decimal \. and one or more digits \d+.
Demo:
console.log( "text 123.12 text".match(/\d+(?:\.\d+)?/g) );
console.log( "The numbers are 132.12, 5, and 123.1.".match(/\d+(?:\.\d+)?/g) );
console.log( "No numbers".match(/\d+(?:\.\d+)?/g) );
You can use RegExp /\d+\.\d+|\d+/g to match digits followed by . character followed by digits, or one or more digits
str.match(/\d+\.\d+|\d+/g)
You can try this one:
var string = "textsometext13.523 after text";
var number = string.match(/[\d\.]+/).toString();
var num = number.split('.');
alert(num[1]); //display the numbers after the period(.) symbol
simply use like this /\d+(?:\.\d+)?/g:
console.log("textsometext13.523 after text".match(/\d+(?:\.\d+)?/g,""))
Alternate, its the reverse process replace the [a-z] same thing will append
console.log("textsometext13.523 after text".replace(/[a-z]/g,""))
This regex should match any number whether it has a decimal or not:
/(\d*\.?\d*)/g
SNIPPET
var btn1 = document.getElementById('btn1');
var inp1 = document.getElementById('inp1');
var out1 = document.getElementById('out1');
btn1.onclick = function() {
var str = inp1.value
var res = str.match(/\d*\.?\d*/g);
out1.innerHTML = res;
}
<input id='inp1'>
<input id='btn1' type='button' value='Extract Numbers'>
<output id='out1'></output>
I'm new to using regexp, can someone give me the regexp that will strip out everything but an integer from a string in javascript?
I would like to take the string "http://www.foo.com/something/1234/somethingelse" and get it down to 1234 as an integer.
Thanks
var str = "something 123 foo 432";
// Replace all non-digits:
str = str.replace(/\D/g, '');
alert(str); // alerts "123432"
In response to your edited question, extracting a string of digits from a string can be simple, depending on whether you want to target a specific area of the string or if you simply want to extract the first-occurring string of digits. Try this:
var url = "http://www.foo.com/something/1234/somethingelse";
var digitMatch = url.match(/\d+/); // matches one or more digits
alert(digitMatch[0]); // alerts "1234"
// or:
var url = "http://x/y/1234/z/456/v/890";
var digitMatch = url.match(/\d+/g); // matches one or more digits [global search]
digitMatch; // => ['1234', '456', '890']
This is just for integers:
[0-9]+
The + means match 1 or more, and the [0-9] means match any character from the range 0 to 9.
uri = "http://www.foo.com/something/1234/somethingelse";
alert(uri.replace(/.+?\/(\d+)\/.+/, "$1"))
Just define a character-class that requires the values to be numbers.
/[^0-9]/g // matches anything that is NOT 0-9 (only numbers will remain)