开发者

Relace a string in a set of strings - regex

开发者 https://www.devze.com 2023-03-03 19:29 出处:网络
How do I replace a string in a long string like below using regex (JS) please? My string could be one of the following:

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

精彩评论

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