Meaningless Drivel is fun!
The moose likes HTML, CSS and JavaScript and the fly likes Dynamic pattern in regular expression Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of OCA Java SE 8 Programmer I Study Guide this week in the OCAJP 8 forum!
JavaRanch » Java Forums » Engineering » HTML, CSS and JavaScript
Bookmark "Dynamic pattern in regular expression" Watch "Dynamic pattern in regular expression" New topic

Dynamic pattern in regular expression

hariharan jayaprakash
Ranch Hand

Joined: Sep 09, 2010
Posts: 64

How to use dynamic pattern in replace method?


Var x=" a "

In below code will trim off the spaces.

x=x.replace(/^\s+|\s+$/g,""); ... so above scenario is working fine. finally i got output is "a"

but if i have scnario like

I have value x="MrArunB.E"

In this i need to remove "Mr"

Var a = "Mr"
Var b = "B.E"

how can i use these variable in replace method with dynamically pattern instead of \s?

x=x.replace(/^\s+|\s+$/g,""); .

I need output only "Arun" ..
Keith Wood
Ranch Hand

Joined: Aug 28, 2012
Posts: 38

Create a new RegExp object with your required pattern:

Author of the upcoming "Extending jQuery" book from Manning.
I agree. Here's the link:
subject: Dynamic pattern in regular expression
It's not a secret anymore!