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

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 diafol

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 diafol

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.