开发者

Relace a string in a set of strings - regex

How do I replace a string in a long string like below using regex (JS) please?

My string could be one of the following:


str = "this may have bgskin-akb4c hello how";
or
str = "have bgskin-a2b3c hello";
or
str = "bgskin-xyz2 hello";
or 
str = "bgskin-bbc";
开发者_开发知识库

in the above string I would like to replace the 2nd part of the word (ex: -akb4c, -xyz2) starting with "bgskin" with a new string value, ex: "have bgskin-a2b3c hello" becomes "have bgskin-newstr hello"

Appreciate your help on this.

Many thanks, L


In Javascript

str.replace(/bgskin-\w+/g, 'bgskin-newstr');


var str = "this may have bgskin-akb4c hello how";
var newstr = str.replace(/(bgskin-)[^\s]+/gi, "$1test");


The gi flags at the end of my regex pattern tell it to do a global and case-insensitive search.

var pattern = /bgskin-[a-z0-9]+/gi;
str.replace(pattern, "bgskin-newstr");

See it working on jsFiddle: http://jsfiddle.net/VMtnW/


In Perl, assuming you always want the replacement string to be the same: s/bgskin-\w+/bgskin-newstr/g

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜