0

I m having a string, I need to check if that string contains any number or not. I found so many answers which only returns true or false Like this. But what I want to do is identify that number and replace it with another string. For example,

let myString = "/example/123/anotherstring" 

or

let myString = "/example/anotherstring/123"

String can be anything like above. Expected output is 123 should be replaced by any other string. like

let expectedString = "/example/replaced/anotherstring" 

or

let expectedString = "/example/anotherstring/replaced"

I Know one way to solve this is, loop this string and find the position of number and then replace that. but I don't want to do that. Is there any better way to do this?

NOTE: The number can be anything, It's not static/known number. So this does not help me.

Any help would be appreciated.

Ushma Joshi
  • 459
  • 6
  • 19

3 Answers3

1

You can use string replace() for this, pass a required regex to fit your requirement.

let myString = "/example/123/anotherstring" 
let newString = myString.replace(/\d+/g, "replaced")
console.log(newString)

 myString = "/example/anotherstring/123"
 newString = myString.replace(/\d+/g, "replaced")
 console.log(newString)
Ashish Ranjan
  • 12,760
  • 5
  • 27
  • 51
  • @JaromandaX Oh, sorry I didn't read your comment in the question, I have read it now. Its a co-incidence that I used the same regex which you had already answered in your comment. And this regex is quite natural and comes to mind first. My answer was incorrect initially coz I did it in hurry. – Ashish Ranjan Apr 25 '19 at 09:41
  • no, it's not a coincidence, it's the only regex that works :p I was being "funny" :p – Jaromanda X Apr 25 '19 at 09:41
0

You can use \d+.

let myString = "/example/123/anotherstring" 

const checkNums = (str) => str.replace(/\d+/g,"replaced")

console.log(checkNums(myString))
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
0

Just use a regular expression to replace all numbers with your alternative string:

const myString = "/example/123/anotherstring";
const expectedString = myString.replace(/[0-9]+/g, "alternativestring")
console.log(expectedString);
fjc
  • 5,590
  • 17
  • 36