简体   繁体   中英

Replace Text in val with array - jquery

I am looking to replace text in a text area value with an array. I have already seen how to replace the text with a value

$("#mySelector").val(function(i, v) { //index, current value
return v.replace("#","Custom Text");
});

But I have multiple items to replace. I have tried && between multiple values but I am clearly doing something wrong.

Here is what I have so far:

$(document).ready(function() {

  $('#submit').click(function() {

    var array = [];

    array[0] = '#1', 'Value 1';
    array[1] = '#2', 'Value 2';
    array[2] = '#3', 'Value 3';


    $('#article').val(function(i,v) {
            return v.replace(
            '$VET','Sebastian Vettel' &&
            '$VETf','Sebastian'
            );
    });
    return false;
});
});

The array is there, but I'd like to know how I can use it in the function for return v.replace. My jQuery is pretty basic, hence my issues. Any ideas are appreciated thanks.

If you want to replace more than one string, you should use several .replace() methods:

return v.replace('str1','Sebastian Vettel')
        .replace('str2','Sebastian');

Instead of using multiple .replace() methods you can also use an object:

var chars = {
   '#1': 'Value 1',
   '#2': 'Value 2'
};

$('#article').val(function(i, v) {
    for(k in chars) {
       if (chars.hasOwnProperty(k)) 
         v = v.replace(k, chars[k]);
    }
    return v;
});

You need to chain your replaces together like this:

. $(document).ready(function() {

$('#submit').click(function() {

var array = [];

array[0] = '#1', 'Value 1';
array[1] = '#2', 'Value 2';
array[2] = '#3', 'Value 3';


$('#article').val(function(i,v) {
        return v.replace(
        '$VET','Sebastian Vettel').replace(
        '$VETf','Sebastian'
        );
});
return false;

}); });

You need to iterate through the array and replace

$(document).ready(function () {

    $('#submit').click(function () {

        var array = [];

        array[0] = ['#1', 'Value 1'];
        array[1] = ['#2', 'Value 2'];
        array[2] = ['#3', 'Value 3'];

        $('#article').val(function (i, v) {
            $.each(array, function (i, arr) {
                v = v.replace(arr[0], arr[1]);
            })
            return v;
        });
        return false;
    });
});

Demo: Fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM