简体   繁体   中英

How to replace specific characters within a string in JavaScript?

Given a string like aaabba , I want a function which turns the a's to b's and the b's to a's , returning bbbaab .

I tried this clumsy one:

var newa = [];
function swit(x) { 
    for (var i = 0; i < x.length; i++) {
        if (x[i] === 'a') {
            newa.push('b');
        } 
        else if (x[i] === 'b') {
            newa.push('a');
        } 
        alert(newa);
    }
}
swit("aaab");

After clicking through a lot of alerts, finally, the last alert shows the intended result. But I want it without commas and at the first place – not after many iterations:

在此处输入图片说明

I also tried the string.replace() Method – in combination with a for -loop:

function swit(x) { 
    for (var i = 0; i < x.length; i++) {
        if (x[i] === 'a') {
            x.replace('a', 'b');
        } 
        else if (x[i] === 'b') {
            x.replace('b', 'a');
        } 
        alert(x);
    }
}
swit("aaab");

But nothing changes. Why?

Could you please give me a hint of what went wrong and how to get the desired result?

Easiest way is to split text to single characters using split , then map array of chars by simply replace a => b and b => a and join it together again, or just use replace

'bbbaab'.split('').map(char => char === 'a' ? 'b' : 'a').join('');

'bbbaab'.replace(/a|b/g, (match) => match === 'a' ? 'b' : 'a');

 function swap(str) { return str.split('').map(char => char === 'a' ? 'b' : 'a').join(''); } function swap2(str) { return str.replace(/a|b/g, (match) => match === 'a' ? 'b' : 'a'); } console.log(swap('bbbaab')); console.log(swap2('bbbaab')); 

var str = "aaab";
str = str.replace(/a|b/g, v => {
       if(v=="a"){
         return "b"
       }else{
         return "a"
       }
    });

console.log(str);

Your first example works but replaces a string with an array of characters (which is different from a string). You can simply join the resulting array to get desired result:

function swit(x) {
    var newa = [];

    for (var i = 0; i < x.length; i++) {
        if (x[i] === 'a') {
            newa.push('b');
        } else if (x[i] === 'b') {
            newa.push('a');
        }
    }

    var arrayJoined = newa.join('');
    alert(arrayJoined);
    return arrayJoined;
}

For your second example, replace replaces all occurences in a string and does not need to be run in a for loop. So what you actually do in your second code sample is: for each character in string: if character is 'a', replace by b. if character is 'b', replace by a for each character in string: if character is 'a', replace by b. if character is 'b', replace by a . Which basically just switches all a 's to b 's and b 's back to a 's. Which results in the same output string as your input string.

You need to move your alert line out of the for loop to the end, and use Array.join() to convert newa into a string without commas.

Also, it would make sense to move the newa array declaration inside the swit function.

Lastly, you should consider also adding an else condition where you just push the exact same current character onto the newa array if it is not an a or b , so the output string length is the same as the original string.

 function swit(x) { var newa = []; for (var i = 0; i < x.length; i++) { if (x[i] === 'a') { newa.push('b'); } else if (x[i] === 'b') { newa.push('a'); } else { newa.push(x[i]) } } alert(newa.join("")); } swit("aaab"); swit("aasdfcvbab"); 

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