CKKiller
CKKiller

Reputation: 1422

trim RegExp result

I'm using RegExp to extract specific words from a string like the following:

<div class = ''></div>class class 

My current RegExp statement is this:

/(<)[^(>)]*(;| |'|&quote;)(class)?( |'|&quote;|=)/gi

In this instance I wan t to match the word 'class' but only if it has specific characters (or ampersands) before and after it. This statement matches:

<div class 

out of the original string, I'm using this in a replace method (to insert text where 'class' was) and I want to keep the other character around it, is there any way of trimming this match down to only select(replace) the word 'class' (in this instance)?

Or is there a better way of doing this? Thanks in advance.

Upvotes: 0

Views: 168

Answers (2)

Andrew D.
Andrew D.

Reputation: 8220

You can use next code to do this job:

var removeSubstring=(function(){
    var fn=function($0,$1,$2,$3){return $1+$3;};
    return function(str,before,after,removed){
        var rg=new RegExp("("+before+")("+removed+")("+after+")","gi");
        return str.replace(rg,fn);
    };
})();

var str="<div class = ''></div>class class <div class ";
var before="<div ";
var after=" ";
var removed="class";

removeSubstring(str,before,after,removed);
// <div  = ''></div>class class <div  

But you must ensure what in before, after and removed strings does not contained special RegExp format characters (such as . [ ] ? * and others, see MDN RegExp). Otherwise you must first escape these special characters in before, after and removed strings.

UPDATE:

You also can use valid regular expression for before, after and removed to make more flexible search. For example next code remove letters 'X', 'V' and 'Z' but not remove 'x', 'v' and 'z':

var str="qXd ezrwsvrVa etxceZd";
var before="q|w|e|r";
var after="a|s|d|f";
var removed="z|x|c|v";

removeSubstring(str,before,after,removed);
// "qd ezrwsvra etxced"

If you need to replace substring with another string you can use next function:

function replaceSubstring(str,before,after,removed,inserted){
    var rg=new RegExp("("+before+")("+removed+")("+after+")","gi");
    return str.replace(rg,function($0,$1,$2,$3){
        // $1 is searched "before" substring
        // $2 is searched "removed" substring
        // $3 is searched "after" substring
        return $1+(inserted||"")+$3;
    });
};


var str="qXd ezrwsvrVa etxceZd";
var before="q|w|e|r";
var after="a|s|d|f";
var removed="z|x|c|v";
replaceSubstring(str,before,after,removed,"DDDD")
// "qDDDDd ezrwsvrDDDDa etxceDDDDd"

Upvotes: 1

Abraham
Abraham

Reputation: 20694

Try this:

var match = /your regex here/.exec(myString)
match = match.replace('class','')

Upvotes: 0

Related Questions