0

I have below code for replace anything apart from number/ float from a string.

const parseNumbers = strInput => strInput
  .trim()
  .replace(/^[@#$%^&*()_+}{|{}[\]/<>,.;'"`~a-z!]*/gi, '')
  .replace(/[^0-9]+[.][0-9]*/g, "");

The following strings are not working with the above regex:

'644322.abc'

While this works '644322.abc.....' gets converted to 644322

'644322.12ac.....' gets converts to 644322.12

But this does not:

'644322.12ac' gets converted to 644322.12ac

'644322.12-1' remains as is 644322.12-1

I want to replace all characters which are not numbers and keep values as number or float.

3
  • Hi i am not here to say something wrong or whatever, just a question, why you replace things unless of checking if they are true? is it user friendly? Commented Jul 1, 2021 at 14:58
  • Good point. Sometimes in data, they have these special characters which need to be discarded. Commented Jul 1, 2021 at 15:09
  • 1
    What is the expected output for 644322.12-1? I suppose 644322.121, right? Or do you only want to keep max 2 fractional digits? Commented Jul 1, 2021 at 17:04

2 Answers 2

4

Can you give an example string? Here is one made up from your question.

let input = "I have below code for replace anything apart from number/ float from a string.The following strings are not working with the above regex:'644322.abc'While this works '644322.abc.....' gets converted to 644322'644322.12ac.....' gets converts to 644322.12But this does not:'644322.12ac' gets converted to 644322.12ac'644322.12-1' remains as is 644322.12-1"

let re = /[+-]?([0-9]*[.])?[0-9]+/g
let m = input.match(re);
console.log(m)

Sign up to request clarification or add additional context in comments.

2 Comments

It will be just a string of numbers like I added in my post. But I think solution provided by you should work
match function creates a different result than needed. I want to replace characters which do not match the condition. Match function creates different set of output on match.
0

You can remove all chars other than digits and dots first, and then remove all dots other than the first one (unless that first dot is at the end of the string) and use

const texts = ['644322.abc', '644322.12ac.....', '644322.12ac', '644322.12-1'];
texts.forEach( text => console.log(
  text,
  '=>',
  text.replace(/[^\d.]+/g, '').replace(/^([^.]*\.)(?!$)|\./g, '$1')
))

Details:

  • .replace(/[^\d.]+/g, '') - removes all chars other than digits and dots
  • .replace(/^([^.]*\.)(?!$)|\./g, '$1') - removes all dots other than the first one that is not at the end of string.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.