File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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
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
jQuery in Action, 3rd edition