开发者

.replace() regex question

开发者 https://www.devze.com 2023-03-11 16:36 出处:网络
I can have a string that looks like this as an example: sometext<a title=\"Wink\"><img src=\"http:\\\\www.seemstatic.com\\images\\transparent.png\"开发者_开发知识库 class=\"emoWink\"><

I can have a string that looks like this as an example:

sometext<a title="Wink"><img src="http:\\www.seemstatic.com\images\transparent.png"开发者_开发知识库 class="emoWink"></a>somemore text<a title="Wink"><img src="http:\\www.seemstatic.com\images\transparent.png" class="emoWink"></a>endof text...

I have the following Javascript that matches the above string, and replaces it with :):

subject = subject.replace(/<a title="Smile"><img.*<\/a>/, ':)');

The catch is it's not greedy... it matches both occurrences rather then just one.

How would I change this code to match just the first occurrence?


you need to make it non greedy by adding a question mark ?

// Greedy quantifiers
String match = find("A.*c", "AbcAbc");  // AbcAbc
match = find("A.+", "AbcAbc");          // AbcAbc

// Nongreedy quantifiers
match = find("A.*?c", "AbcAbc");        // Abc
match = find("A.+?", "AbcAbc");         // Abc

So in your case, something like

subject = subject.replace(/<a title="Smile"><img.*?<\/a>/, ':)');


Don't do this with regex. You're already using jQuery, so you can use jQuery's DOM traversal methods:

yourString = $('<span>' + yourString + '</span>')
                 .find('a[title="Wink"]')
                     .replaceWith(';)')
                 .end()
                 .html();


Technically this is not a jquery question, it is a javascript question, since the replace here is on a String object.

You can greedy replace with subject.replace(/search/g, 'replacement');

The g modifier makes it replace all instances.

You problem might be better solved with a jQuery approach though, using css selectors: eg. $('.a[title=Smile]').replaceWith(';)')

0

精彩评论

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