需要从字符串中去除特殊字符,并将空格替换为_。

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

need to remove special character from string and space replace with _

问题

输出应该是 "mech_electronics",但现在我得到的输出是 "mech_electronic_"。

英文:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

let updateStreamSelectedCourse = &#39;mech (electronics)&#39;.replace(/([^\w]+)/g, &#39;_&#39;, );
console.log(updateStreamSelectedCourse);

<!-- end snippet -->

output should be mech_electronics

but now im geting output is mech_electronic_

答案1

得分: 1

你不能用不同的字符替换它们,但可以将最后一个 _ 替换为以下内容:

let updateStreamSelectedCourse = 'mech (electronics)'.replace( /([^\w]+)/g, '_', ).replace(/_$/,"");
console.log(updateStreamSelectedCourse)
英文:

You can't replace them with different characters, but You can replace the last _ with the following

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

let updateStreamSelectedCourse = &#39;mech (electronics)&#39;.replace( /([^\w]+)/g, &#39;_&#39;, ).replace(/_$/,&quot;&quot;);
console.log(updateStreamSelectedCourse)

<!-- end snippet -->

答案2

得分: 0

/_$/g,' '应该是你需要的:

let updateStreamSelectedCourse = 'mech (electronics)'.replace(/([^\w]+)/g, '_').replace(/_$/g,'');
console.log(updateStreamSelectedCourse)
英文:

/_$/g,&#39;&#39; should be what you need :

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

let updateStreamSelectedCourse = &#39;mech (electronics)&#39;.replace( /([^\w]+)/g, &#39;_&#39;, ).replace(/_$/g,&#39;&#39;);
console.log(updateStreamSelectedCourse)

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年3月9日 15:40:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/75681664.html
匿名

发表评论

匿名网友

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

确定