Ming
Ming

Reputation: 71

How to avoid duplicate replacement in Jquery regular matching

I have a string like

var str = "图1,good boy,图11,图2,图1,good girl";

And a regex like

var regex = new RegExp("图[0-9]{1,2}","g");

then I use

 var matchArray = str.match(regex) 

to return Array which are ["图1","图11","图2","图1"],Then I will remove the duplicate data to change the array to ["图1","图11","图2"];what I want to do is replace the matched words to wrap "<span>matchWord</span>"

for(var x = 0;x < matchArray.length; x++){
  var temp = "<span>"+matchArrat[x]+"</span";
  var tempRegex = new RegExp(matchArray[x],"g");
  str = str.replace(tempRegex,temp);
}

But there is a problem.If replace image1 first,it will wrong replace the str's "图1" of "图11"。If replace "图11" with "<span>图11</span>" first,When replace 图1,it will wrong replace "图1" of "<span>图11</span>" This is a simple example.the practical condition is complex than this example.

Upvotes: 0

Views: 73

Answers (2)

Ming
Ming

Reputation: 71

I find another method to solve this problem. First,create a function to generate a uuid.

function createUUID() {
// http://www.ietf.org/rfc/rfc4122.txt
var s = [];
var hexDigits = "0123456789abcdef";
for (var i = 0; i < 36; i++) {
    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
}
s[14] = "4";  // bits 12-15 of the time_hi_and_version field to 0010
s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);  // bits 6-7 of the clock_seq_hi_and_reserved to 01
s[8] = s[13] = s[18] = s[23] = "-";

var uuid = s.join("");
return uuid;

} then,loop the matchArray and use a object to record

for(var i = 0 ; i < matchArray.length; i++){
 var obj = {};
 obj[matchArray[i]] = createUUID();
};

var uuids = createUUID(); then replace the matchWord with uuid

   for (var i = 0 ; i < matchArray.length ; i++) {
         var matchWord = matchArray[i];
         var replaceRegex = new RegExp(matchWord,"g");
         var tempStr = uuids[matchArray[i]];
         var replaceHtml = "<span >"+tempStr+"</span>"
         replaceText = replaceText.replace(replaceRegex,replaceHtml);
  }

after replace this,then loop the object property

for ( var key in uuids){
   var tempRegex = new RegExp(uuids[key],"g");
   replaceText = replaceText.replace(tempRegex,key);
   }

Because the practical condition is complex than the example,so this method can solve the unregular string

Upvotes: 0

Nick
Nick

Reputation: 147166

One way to do this is to split your string on ,, and then wherever a value matches 图[0-9]{1,2}, replace the value with <span>value</span> before reassembling the string:

var str = "图1,good boy,图11,图2,图1,good girl";
console.log(str
            .split(',')
            .map(v => v.match(/图[0-9]{1,2}/u) ? `<span>${v}</span>` : v)
            .join(',')
            );

Upvotes: 1

Related Questions