how to find the first number from string in js(javascript)? [duplicate] - javascript

This question already has answers here:
Get the first integers in a string with JavaScript
(5 answers)
Closed 6 months ago.
How to find the first number from string in javascript?
var string = "120-250";
var string = "120,250";
var string = "120 | 250";

Here is an example that may help you understand.
Use the search() method to get the index of the first number in the string.
The search method takes a regular expression and returns the index of the first match in the string.
const str = 'one 2 three 4'
const index = str.search(/[0-9]/);
console.log(index); // 4
const firstNum = Number(str[index]);
console.log(firstNum); // 2

Basic regular expression start of string followed by numbers /^\d+/
const getStart = str => str.match(/^\d+/)?.[0];
console.log(getStart("123,456"));
console.log(getStart("123-456"));
console.log(getStart("123|456"));
console.log(getStart("xxx,xxx"));
Or parseInt can be used, but it will drop leading zeros.
const getStart = str => parseInt(str, 10);
console.log(getStart("123,456"));
console.log(getStart("123-456"));
console.log(getStart("123|456"));
console.log(getStart("xxx,xxx"));

Related

Javascript - How to get a list of strings between two characters [duplicate]

This question already has answers here:
Regex to find or extract strings between the "<>" angle brackets
(3 answers)
Find substring between angle brackets using jQuery
(3 answers)
Regex to get string between curly braces
(16 answers)
Regular Expression to get a string between parentheses in Javascript
(10 answers)
Closed 4 months ago.
How can implement a function that returns a list of characters between two characters?
const string = "My name is <<firstname>> and I am <<age>>";
const getVariables = (string) => {
// How do I implement?
}
console.log(getVariables(string)); // ['firstname', 'age']
PS: I realize there are multiple answers on how to do something similar, but all of them only work for getting first instance and not all occurrences.
Assuming this is some kind of templating, you can proceed like this:
let format = (str, vars) =>
str.replace(/<<(\w+)>>/g, (_, w) => vars[w]);
//
const tpl = "My name is <<firstname>> and I am <<age>>";
console.log(
format(tpl, {firstname: 'Bob', age: 33})
)
You could search for string which has the starting pattern and end pattern with look behind and look ahead.
const
string = "My name is <<firstname>> and I am <<age>>",
parts = string.match(/(?<=\<\<).*?(?=\>\>)/g);
console.log(parts);
You could use regex, group, matchAll and get the first group
const string = "My name is <<firstname>>, from <<place>>, and I am <<age>>"
const getVariables = string => {
return [...string.matchAll(/<<(\w+)>>/g)].map(match => match[1])
}
console.log(getVariables(string))

JavaScript count digits in a string [duplicate]

This question already has answers here:
Count the number of integers in a string
(6 answers)
Closed 1 year ago.
I want to know how many digits 0 to 9 are in a string:
"a4 bbb0 n22nn"
The desired answer for this string is 4.
My best attempt follows. Here, I'm iterating through each char to check if it's a digit, but this seems kind of heavy-handed. Is there a more suitable solution?
const str = 'a4 bbb0 n22nn'
const digitCount = str.split('').reduce((acc, char) => {
if (/[0-9]/.test(char)) acc++
return acc
}, 0)
console.log('digitCount', digitCount)
With the regular expression, perform a global match and check the number of resulting matches:
const str = 'a4 bbb0 n22nn'
const digitCount = str.match(/\d/g)?.length || 0;
console.log('digitCount', digitCount)

SubString in JavaScript [duplicate]

This question already has answers here:
How to get the nth occurrence in a string?
(14 answers)
Closed 2 years ago.
For example, I have a string like following
var string = "test1;test2;test3;test4;test5";
I want the following substring from the above string, I don't know the startIndex, the only thing I can tell substring should start after the second semicolon to till the end.
var substring = "test3;test4;test5";
Now I want to have substring like following
var substring2 = "test4;test5"
How to achieve this in JavaScript
You mean this?
const string = "test1;test2;test3;test4;test5";
const arr = string.split(";")
console.log(arr.slice(2).join(";")); // from item #2
console.log(arr.slice(-2).join(";")) // last 2 items
If the string is very long, you may want to use one of these versions
How to get the nth occurrence in a string?
As a function
const string = "test1;test2;test3;test4;test5";
const restOfString = (string,pos) => {
const arr = string.split(";")
return arr.slice(pos).join(";"); // from item #pos
};
console.log(restOfString(string,2))
console.log(restOfString(string,3))
Try to use a combination of string split and join to achieve this.
var s = "test1;test2;test3;test4;test5";
var a = s.split(";")
console.log(a.slice(3).join(";"))

splitting a string with a decimal number and some characters [duplicate]

This question already has answers here:
Splitting a string at special character with JavaScript
(8 answers)
How do I split a string, breaking at a particular character?
(17 answers)
Closed 4 years ago.
I have strings like:
'1234picas'
'1234 px'
'145.4us'
I want to split them in two parts: the numeric part and the non numeric one. For example: '1234.4us' need to be splitted in '1234.4' and 'us'. I am tempted to insert a separator between the last digit and the non numeric and use split but is there a better way to do this in JavaScript
Thanks
Note: this is not the slitting of a string at special char. it could be converted to that but this is what I am trying to avoid.
You can do it using String.prototype.match():
const a = '1234picas';
const b = '1234 px';
const c = '145.4us';
function split(input) {
const splitArray = input.match(/([\d\.]+)(.*)/); // match only digits and decimal points in the first group and match the rest of the string in second group
return {
numeric: splitArray[1],
nonnumeric: splitArray[2],
};
}
console.log(split(a));
console.log(split(b));
console.log(split(c));
Regex explanation | Regex101
You can use .split with a regex using a lookahead:
str.split(/(?=[^\d.-])/g))
.map(y => [
y[0],
y.slice(1).join('').trim()
])
x = ["1234picas", "1234 px", "145.4us"];
console.log(x.map(y =>
y.split(/(?=[^\d.-])/g))
.map(y => [
y[0],
y.slice(1).join('').trim()
])
)
You can do like this in javascript to split:
var myString = '145.4us';
var splits = myString.split(/(\d+\.?\d+)/);
console.log(splits);
here's one way to do it using parseFloat() and slice() , you can add it to the Sting.prototype if you want :
const str1 = '1234picas',
str2 = '1234 px',
str3 = '145.4us';
String.prototype.split = function () {
const num = parseFloat(this);
const alph = this.slice(num.toString().length, this.length)
return {
num,
alph
}
}
console.log(str1.split());
console.log(str2.split());
console.log(str3.split());
This may help you:
var a = "4343.453fsdakfjdsa";
a.match(/[a-zA-Z]+|[\d\.?]+/ig);
MDN for String.match
It basically says match the alphabetical letters OR match numbers with an optional period. The ig is insensitive (which is not really needed) and global as in don't return on the first match, keep going until all of the string has been parsed.
Regex!
Here is how it works: https://regex101.com/r/XbI7Mq/1
const test = ['1234picas', '1234 px', '145.4us', 'no'];
const regex = /^(\d+\.?\d+)\s?(.*)/;
test.forEach(i => {
const result = regex.exec(i);
if (result) {
console.log(result[1], result[2])
}
});

How can I extract only the integer from a String JavaScript [duplicate]

This question already has answers here:
How to find a number in a string using JavaScript?
(9 answers)
Closed 6 years ago.
I have a string that looks like:
var a = "value is 10 ";
How would I extract just the integer 10 and put it in another variable?
You could use a regex:
var val = +("value is 10".replace(/\D/g, ""));
\D matches everything that's not a digit.
you can use regexp
var a = "value is 10 ";
var num = a.match(/\d+/)[0] // "10"
console.log ( num ) ;
You can use some string matching to get an array of all found digits, then join them together to make the number as a string and just parse that string.
parseInt(a.match(/\d/g).join(''))
However, if you have a string like 'Your 2 value is 10' it will return 210.
You do it using regex like that
const pattern = /\d+/g;
const result = yourString.match(pattern);

Categories

Resources