开发者

JavaScript text manipulation

开发者 https://www.devze.com 2022-12-19 17:30 出处:网络
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开发者_Go百科 I do it?

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开发者_Go百科 I do it?

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


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


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消