2

Using JavaScript and I want to replace any text between @anytext@ with some text. I want to make it generic so I am thinking to make use of regular expression. How do I do it?

Example:replace('@hello@','Hi')

Yacoby
55.6k16 gold badges119 silver badges121 bronze badges
asked Feb 11, 2010 at 10:10
2
  • Changed everything from jQuery to JavaScript, as it has nothing to do with jQuery. Commented Feb 11, 2010 at 10:18
  • I need to make little manipulation in this.I need to retrieve the matched text and then replace the matched text.Something like this Replace("@anytext@",<a href=#>@anytext@</a>) My string can have @anytext@ any where in string multiple times. Commented Feb 11, 2010 at 11:12

3 Answers 3

2

Try this:

str.replace(/@[^@]+@/g, 'Hi')

This will remove any sequences of @ ... @ globally with Hi.


Edit Some explanation:

  • /.../ is the regular expression literal syntax in JavaScript
  • @[^@]+@ describes any sequence of a literal @, followed by one or more (+ quantifier) characters that is not a @ (negated charcater class [^@]), followed by a literal @
  • the g flag in /.../g allows global matches; otherwise only the first match would be replaced
answered Feb 11, 2010 at 10:17
Sign up to request clarification or add additional context in comments.

1 Comment

Works.Please provide some explanation.I didnt find any where so I can create my own Regular expressions.Thanks
0

You can use the regex function of jquery to accomplish that... So find the @'s with a regular expression and afterwards use the replace function with the text you want.

answered Feb 11, 2010 at 10:17

Comments

0

This has nothing to do with jQuery, but just plain old javascript.

var regexp = new RegExp("@([^@]+)@");
text.replace(re, "replacement text");

But what do you mean by generic? How generic do you want to make it?

You can find more information about regular expressions on http://regexp.info including how to use in in Javascript

answered Feb 11, 2010 at 10:19

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.