Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Dynamic pattern in regular expression

 
hariharan jayaprakash
Ranch Hand
Posts: 67
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

How to use dynamic pattern in replace method?

Scenario:

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
Author
Ranch Hand
Posts: 38
jQuery
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Create a new RegExp object with your required pattern:

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic