1

Need a regular expression. If I want to replace "abcdf" with "PPP" in

XabcdfX is xxxxxxx. <MabcdfM> has xxxxx. abcdf is xxxxxxx. <FabcdfF> zxabcdf abcdf.

then the expected output

XPPPX is xxxxxxx. <MabcdfM> has xxxxx. PPP is xxxxxxx. <FabcdfF> zxPPP PPP.

abcdf can be a whole string or even can be a substring. It will be only alphanumeric. It can only be replaced when it does not come between < >.

I need to do it using javascript replace method. Please help me.

3
  • This question makes zero sense. Commented Nov 23, 2011 at 10:50
  • 2
    Unlike Switz I think the question is pretty clear, but I'd like to see what you've tried so far. Also, what if the input string has something like "The number 3 < 5. abcdf But 6 > 2." Commented Nov 23, 2011 at 10:55
  • This question looks like this other one: stackoverflow.com/questions/8214777/… Commented Nov 23, 2011 at 11:01

4 Answers 4

3

You can do it using a callback to replace:

s = s.replace(/abcdf|(<[^>]*>)/g, function(g0,g1){return g1 ? g1: 'PPP';});

Working Example: http://jsbin.com/abakax

Obviously, this will fail if you have nested or non-matching pairs of Angle brackets.

Sign up to request clarification or add additional context in comments.

Comments

1

Assuming your "tags" cannot be nested, you can use a lookahead assertion:

s.replace(/abcdf(?=[^<>]*(<|$))/g, "PPP")

Comments

0

if you can be sure, that there is nothing like >, I would use the indexOf-function iteratively rather than using a regex:

index = string.indexOf("<", lastIndex);
index = string.indexOf(">", index);
index = string.indexOf("abcd", index);
string = string.substring(0, index)+"PPP"+string.substring(index+4);

Comments

0
var collect = function (s, re)
{
  var rv = [];
  for (var m; m = re.exec(s); rv.push(m));
  return rv;
}
var s = "XabcdfX is xxxxxxx. <MabcdfM> has xxxxx. abcdf is xxxxxxx. <FabcdfF> zxabcdf abcdf."
var tags = collect(s, /<[^>]*>/g);
var matches = collect(s, /abcdf/g);

console.log("INPUT:", s)

var r = s

MATCH: for (var i = 0, j = 0; i < matches.length; ++i) {
  var m = matches[i]
  var mbeg = m.index
  var mend = mbeg + m[0].length
  TAG: for (; j < tags.length; ++j) {
    var t = tags[j]
    var tbeg = t.index
    var tend = tbeg + t[0].length
    if (tend < mbeg)
      continue TAG
    if (tbeg < mbeg && tend > mend)
      continue MATCH
    if (tbeg > mbeg)
      break TAG
  }
  r = r.substr(0, mbeg) + m[0].toUpperCase() + r.substr(mbeg + m[0].length)
}
console.log("RESULT:", r)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.