使用JavaScript将字符串中的所有字符替换为 “p”,除了 “o”。

huangapple go评论54阅读模式
英文:

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 (or replaceAll).
  • 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 = &quot;fgyerfgehooefwfweeo&quot;;
let res = str.replace(/[^o]/g, &#39;p&#39;);
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(&quot;fgyerfgehooefwfweeo&quot;.split(&#39;&#39;).map(chr =&gt; chr !== &#39;o&#39; ? &#39;p&#39; : chr).join(&#39;&#39;))

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年3月4日 03:29:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/75631178.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定