how to .replace() the 'error'? only use a and b

var str = 'bla bla anything error anything bla bla';
var a = 'anything', b = a;

im not good with regular expressions so im asking for how to do this with variables so i can set them up all by myself

Dani AI

Generated

If the goal is to replace only the unknown text between two known markers (keeping the markers), build a regex from your variables and use capturing groups to preserve the edges. Always escape user-provided markers so special regex characters do not break the pattern.

function escapeRegExp(s) {
  return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}

function replaceBetween(str, start, end, replacement) {
  const s = escapeRegExp(start);
  const e = escapeRegExp(end);
  // Non-greedy: nearest end
  const re = new RegExp(`(${s})([\\s\\S]*?)(${e})`, "g");
  return str.replace(re, `$1${replacement}$3`);
}

// Greedy variant (use the last 'end' after the first 'start'):
// const re = new RegExp(`(${s})([\\s\\S]*)(${e})`, "g");
  • Use [\\s\\S] so matches can span newlines without relying on dotAll. In modern engines you can use the s flag with .*? instead; see MDN on the dotAll flag at MDN RegExp.prototype.dotAll.
  • If you prefer to replace only the middle via lookarounds, modern browsers support lookbehind: new RegExp('(?<=' + s + ')[\\s\\S]*?(?=' + e + ')','g') (verify compatibility; see MDN Lookahead/Lookbehind).

A regex-free alternative mirrors what you tried but avoids replacing by substring content (which may appear elsewhere):

function replaceBetweenSlice(str, start, end, replacement) {
  const i = str.indexOf(start);
  if (i === -1) return str;
  const j = str.indexOf(end, i + start.length);
  if (j === -1) return str;
  return str.slice(0, i + start.length) + replacement + str.slice(j);
}

References: MDN String.prototype.replace, MDN Regular expressions guide.

Recommended Answers

All 8 Replies

var a = str.replace(/error/,'my replace')
or
str.replace(/anything.*anything/,'anything my replace anything')
if I understand correctly

no i mean something like str = str.replace(str.substring(str.indexOf(a)+a.length, str.lastIndexOf(a)), 'whatever')

what's wrong with andris' answer?:

var a = "bla bla anything error anything bla bla";
a = a.replace("error", "whatever");

I want to replace the word "error" without knowing what the word will be, the word "error" is just there for example but could be anything

so you don't know what comes before, you don't know what the word-to-replace will be and you don't know what comes after? i think you'll have to know something about what you're dealing with.

Member Avatar for Member #120589

OK, so do you mean a function like...

function myReplace(search,replace,string)
{
    var pattern = new RegExp(search,"g");
    return string.replace(pattern,replace);
}

var search = 'me';
var replace = 'you';
var string = 'help me to help you';

alert(myReplace(search,replace,string));

Obviously the variables can be set from anything you want

I mean replace text between two known strings but you don't know what any of the text in the middle is like this.

var str = "abcdefghijklmnopqrstuvwxyz";
var start = "def";
var end = "nop";
str = str.replace(str.substring(str.indexOf(start)+start.length, str.lastIndexOf(end)), '*');
alert(str);
Member Avatar for Member #120589

Unfortunately, js does not do look-behind regex , so it's a fudge (I'm not v. hot on regex either ):

<script>
function myReplace(string,replacement,start,ending)
{
    replacement = start + ' ' + replacement;

     var pattern = new RegExp(start + ' \.+(?=' + ending + ')','g');

    return string.replace(pattern, replacement + ' ');
}

var start = 'a';
var ending = 'goodfornothing';
var string = 'You strike me as a layabout goodfornothing';
var replacement = 'useless brain-dead';

alert(myReplace(string,replacement,start,ending));
</script>

This is just a rough 'first thoughts' snippet. It certainly hasn't been tested thoroughly and I know it will fail with certain characters. But may be enough to get started with.

commented: thanks :) +1
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.