Extract numbers from a string in JavaScript

To extract numbers from a string in JavaScript, you can use regular expressions. Regular expressions allow you to match and extract patterns from strings. Here's a function that extracts numbers from a given string:

function extractNumbersFromString(inputString) {
  // Create a regular expression to match numbers (both integers and decimals)
  const regex = /[-+]?\d+(\.\d+)?/g;

  // Use the match() method with the regex on the input string
  const numbersArray = inputString.match(regex);

  // If no numbers are found, return an empty array
  if (!numbersArray) {
    return [];
  }

  // Convert the matched strings to actual numbers and return the result
  return numbersArray.map((number) => parseFloat(number));
}

// Test the function
const inputString = "Hello, I have 42 apples and 3.14 bananas.";
const extractedNumbers = extractNumbersFromString(inputString);
console.log(extractedNumbers); // Output: [42, 3.14]

In this code, we define a function extractNumbersFromString that takes a inputString as a parameter. The regular expression /[-+]?\d+(\.\d+)?/g matches both integers and decimals, including positive or negative numbers.

The match() method is used on the input string with the regex to find all matches of numbers in the string. If no numbers are found, it returns null, and in that case, we return an empty array.

The map() method is used to convert the matched strings to actual numbers using parseFloat(). Finally, the function returns an array of extracted numbers.

Note that this code will extract numbers with or without a decimal point. If you only want to extract integers, you can modify the regular expression to /[-+]?\d+/g.

댓글

이 블로그의 인기 게시물

Delete topic on Kafka, 카프카 토픽 삭제하기

how to delete all issues on project in sentry, 센트리 이슈 삭제하기

ftplib.error_perm: 550 Permission denied

Pyspark 를 사용한 테이블 조인, table join with pyspark

[OS_Linux_Ubuntu] telnet & ssh 설치와 설정 (installation / configuration)

10 Python Functions Every Data Scientist Must Memorize

Python program to convert an .xlsx file to JSON using the openpyxl library

Read a file in Java, 자바 파일 읽기

Auto-populate a calendar in an MUI (Material-UI) TextField component