0

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

Edited by nouth

4
Contributors
8
Replies
31
Views
3 Years
Discussion Span
Last Post by diafol
0

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

Edited by AndrisP

0

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

Edited by nouth

0

what's wrong with andris' answer?:

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

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

0

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.

0

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

0

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);
1

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.

Votes + Comments
thanks :)
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.