英文:
Use JavaScript to replace all characters in string with "p" except "o"
问题
我想用 "p" 替换字符串 myString 中的所有字符,除了 "o"。
例如:
"fgyerfgehooefwfweeo"
应该变成
"pppppppppoopppppppo"
我尝试过:
myString.replaceAll('[^o]*', 'p')
英文:
I would like to replace all characters in a string myString with "p", except "o".
For example:
"fgyerfgehooefwfweeo"
should become
"pppppppppoopppppppo"
I tried:
myString.replaceAll('[^o]*/g', 'p')
答案1
得分: 1
- 使用正则表达式字面量而不是字符串来替换
replace(或replaceAll)。 - 不要在字符类后面使用
*;否则,连续出现的不是 "o" 的多个字符将被合并为单个 "p"。
let str = "fgyerfgehooefwfweeo";
let res = str.replace(/[^o]/g, 'p');
console.log(res);
英文:
- Pass a regular expression literal instead of a string to
replace(orreplaceAll). - Do not use
*after the character class; otherwise, multiple consecutive characters that are not "o" will be collapsed into a single "p".
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
let str = "fgyerfgehooefwfweeo";
let res = str.replace(/[^o]/g, 'p');
console.log(res);
<!-- end snippet -->
答案2
得分: 1
以下是翻译好的部分:
Simple way without using Regex:
这是一个不使用正则表达式的简单方法:
which String.split() the string into chars and do Array.map() with condition on letter 'o' then finally Array.join() them back.
将字符串使用 String.split() 分割成 chars,然后使用带有字母 'o' 条件的 Array.map() 处理,最后再将它们使用 Array.join() 连接回来。
英文:
Simple way without using Regex:
which String.split() the string into chars and do Array.map() with condition on letter 'o' then finally Array.join() them back.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
console.log("fgyerfgehooefwfweeo".split('').map(chr => chr !== 'o' ? 'p' : chr).join(''))
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论