简体   繁体   English

如何在JavaScript中替换字符串中的特定字符?

[英]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 . 给定像aaabba这样的字符串,我想要一个函数,将a转换b ,将b转换a ,返回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: 我还尝试了string.replace()方法–与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 最简单的方法是使用split将文本分割为单个字符,然后通过简单地替换a => bb => a并将字符映射到字符数组,然后再次join其连接在一起,或者仅使用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: 您可以简单地join结果数组以获得所需的结果:

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. 对于第二个示例, replace替换字符串中所有出现的内容,并且不需要在for循环中运行。 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 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. 基本上,这只是将所有a切换为b ,而b切换回a 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. 您需要将警报行从for循环中移到末尾,并使用Array.join()newa转换为不带逗号的字符串。

Also, it would make sense to move the newa array declaration inside the swit function. 此外,它将使意义移动newa内部数组声明swit功能。

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. 最后,您还应该考虑添加else条件,如果不是ab ,则只需将完全相同的当前字符推入newa数组,因此输出字符串的长度与原始字符串相同。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 对于这种特定情况,如何使用 JavaScript 替换字符串中的所有字符:replace 。 经过 _ - How to replace all characters in a string using JavaScript for this specific case: replace . by _ 如何替换字符串开头和其中的特定位置的字符? - How to replace characters at the start of a string and specific locations within it? 如何在字符串中递归替换字符 - How to replace characters recursively within a string 如何使用 JavaScript 将一个字符串中找到的任何字符替换为另一个字符串 - How to use JavaScript to replace any characters found within one string from another string Node.js:如何用javascript中的其他字符替换数组中的某些字符 - Nodejs: How to replace certain characters within an array with other characters in javascript Javascript 替换字符串字符 - Javascript replace string characters 如何在javascript中的字符串中替换字符串的值 - How to replace the value of a string within a string in javascript 如何替换字符串 JavaScript 中的转义字符 - How to replace escape characters in a string JavaScript Javascript-从值在特定字符之间的字符串中替换子字符串 - Javascript - Replace substring from string where the value is between specific characters 如何在JavaScript中更改字符串中的各个字符 - How to change individual characters within a string in JavaScript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM