Extract Numbers between text in Javascript? - javascript

I have a string as a1234b5.
I am trying to get 1234 (in between a and b5). i tried the following way
number.replace(/[^0-9\.]/g, '');
But it's giving me like 12345. But I need 1234. how to achieve this in Javascript ?

You can use:
var m = 'a1234b5'.match(/\d+/);
if (m)
console.log(m[0]);
//=> "1234"

slighty different approach
var a = "a1234b5243,523kmw3254n293f9823i32lia3un2al542n5j5j6j7k7j565h5h2ghb3bg43";
var b;
if ( typeof a != "undefined" )
{
b = a.match( /[0-9]{2,}/g );
console.log( b );
}
no output if a isn't set.
if a is empty => null
if somethings found => ["1234", "5243", "523", "3254", "293", "9823", "32", "542", "565", "43"]

Assuming that there are always letters around the numbers you want and that you only care about the very first group of numbers that are surrounded by letters, you can use this:
("abc123456def1234ghi123".match(/[^\d](\d+)[^\d]/) || []).pop()
// "123456"

var number = 'a1234b5';
var firstMatch = number.match(/[0-9]+/);
var matches = number.match(/[0-9]+/g);
var without = matches.join('');
var withoutNum = Number(without);
console.log(firstMatch); // ["1234"]
console.log(matches); // ["1234","5"]
console.log(without); // "12345"
console.log(withoutNum); // 12345
I have a feeling that number is actually a hexadecimal. I urge you to update the question with more information (i.e. context) than you're providing.

It's not clear if a and b are always part of the strings you are working with; but if you want to 'extract' the number out, you could use:
var s = "a1234b5",
res = s.match(/[^\d](\d+)[^\d]/);
// res => ["a1234b", "1234"]
then, you could reassign or do whatever. It's not clear what your intention is based on your use of replace. But if you are using replace to convert that string to just the number inside the [a-z] characters, this would work:
s.replace(/[^\d](\d+)[^\d](.*)$/, "$1")
But, that's assuming the first non-digit character of the match has nothing before it.

Related

How to String include after character in nodejs, JavaScript

I want to do this in node.js
example.js
var str = "a#universe.dev";
var n = str.includes("b#universe.dev");
console.log(n);
but with restriction, so it can search for that string only after the character in this example # so if the new search string would be c#universe.dev it would still find it as the same string and outputs true because it's same "domain" and what's before the character in this example everything before # would be ignored.
Hope someone can help, please
Look into String.prototype.endsWith: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith
First, you need to get the end of the first string.
var ending = "#" + str.split("#").reverse()[0];
I split your string by the # character, so that something like "abc#def#ghi" becomes the array ["abc", "def", "ghi"]. I get the last match by reversing the array and grabbing the first element, but there are multiple ways of doing this. I add the separator character back to the beginning.
Then, check whether your new string ends the same:
var n = str.endsWith(ending);
console.log(n);
var str = "a#universe.dev";
var str2 = 'c#universe.dev';
str = str.split('#');
str2 = str2.split('#');
console.log(str[1] ===str2[1]);
With split you can split string based on the # character. and then check for the element on position 1, which will always be the string after #.
Declare the function
function stringIncludeAfterCharacter(s1, s2, c) {
return s1.substr(s1.indexOf(c)) === s2.substr(s2.indexOf(c));
}
then use it
console.log(stringIncludeAfterCharacter('a#universe.dev', 'b#universe.dev', '#' ));
var str = "a#universe.dev";
var n = str.includes(str.split('#')[1]);
console.log(n);
Another way !
var str = "a#universe.dev";
var n = str.indexOf(("b#universe.dev").split('#')[1]) > -1;
console.log(n);

I need help getting the first n characters of a string up to when a number character starts

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)

Get values from string through RegEx

I'm trying to get size values from a strings, which looks like:
https://example.com/eb5f16e5-9b3d-cfcd-19b0-75c6ace724e1/size/80x90/center/
I'm using match method and following RegEx:
'...'.match(/\/(\d+)x(\d+)\//g)
I hoped that the parentheses help to highlight the numbers:
But match returns only ["/80x90/"] without separate size values, like ["/80x90/", "80", "90"].
What am I'm doing wrong?
Here you can test my RegEx.
You don't need g modifier, without it you can get matching groups:
var url = 'https://example.com/eb5f16e5-9b3d-cfcd-19b0-75c6ace724e1/size/80x90/center/';
var res = url.match(/\/(\d+)x(\d+)\//);
console.log(res);
RegExp#exec will return all the captured group including the captured subexpression.
var url = 'https://example.com/eb5f16e5-9b3d-cfcd-19b0-75c6ace724e1/size/80x90/center/';
var patt = /\/(\d+)x(\d+)\//g;
var result = [];
while ((result = patt.exec(url)) !== null) {
console.log(result);
}

Using RegExp to substring a string at the position of a special character

Suppose I have a sting like this: ABC5DEF/G or it might be ABC5DEF-15 or even just ABC5DEF, it could be shorter AB7F, or AB7FG/H.
I need to create a javascript variable that contains the substring only up to the '/' or the '-'. I would really like to use an array of values to break at. I thought maybe to try something like this.
...
var srcMark = array( '/', '-' );
var whereAt = new RegExp(srcMark.join('|')).test.str;
alert("whereAt= "+whereAt);
...
But this returns an error: ReferenceError: Can't find variable: array
I suspect I'm defining my array incorrectly but trying a number of other things I've been no more successful.
What am I doing wrong?
Arrays aren't defined like that in JavaScript, the easiest way to define it would be with:
var srcMark = ['/','-'];
Additionally, test is a function so it must be called as such:
whereAt = new RegExp(srcMark.join('|')).test(str);
Note that test won't actually tell you where, as your variable suggests, it will return true or false. If you want to find where the character is, use String.prototype.search:
str.search(new RegExp(srcMark.join('|'));
Hope that helps.
You need to use the split method:
var srcMark = Array.join(['-','/'],'|'); // "-|/" or
var regEx = new RegExp(srcMark,'g'); // /-|\//g
var substring = "222-22".split(regEx)[0] // "222"
"ABC5DEF/G".split(regEx)[0] // "ABC5DEF"
From whatever i could understand from your question, using this RegExp /[/-]/ in split() function will work.
EDIT:
For splitting the string at all special characters you can use new RegExp(/[^a-zA-Z0-9]/) in split() function.
var arr = "ABC5DEF/G";
var ans = arr.split(/[/-]/);
console.log(ans[0]);
arr = "ABC5DEF-15";
ans = arr.split(/[/-]/);
console.log(ans[0]);
// For all special characters
arr = "AB7FG/H";
ans = arr.split(new RegExp(/[^a-zA-Z0-9]/));
console.log(ans[0]);
You can use regex with String.split.
It will look something like that:
var result = ['ABC5DEF/G',
'ABC5DEF-15',
'ABC5DEF',
'AB7F',
'AB7FG/H'
].map((item) => item.split(/\W+/));
console.log(result);
That will create an Array with all the parts of the string, so each item[0] will contain the text till the / or - or nothing.
If you want the position of the special character (non-alpha-numeric) you can use a Regular Expression that matches any character that is not a word character from the basic Latin alphabet. Equivalent to [^A-Za-z0-9_], that is: \W
var pattern = /\W/;
var text = 'ABC5DEF/G';
var match = pattern.exec(text);
var position = match.index;
console.log('character: ', match[0]);
console.log('position: ', position);

Adding Dashes to a number without many lines of code

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'

Categories