英文:
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 = 'mech (electronics)'.replace(/([^\w]+)/g, '_', );
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 = 'mech (electronics)'.replace( /([^\w]+)/g, '_', ).replace(/_$/,"");
console.log(updateStreamSelectedCourse)
<!-- end snippet -->
答案2
得分: 0
/_$/g,' '
应该是你需要的:
let updateStreamSelectedCourse = 'mech (electronics)'.replace(/([^\w]+)/g, '_').replace(/_$/g,'');
console.log(updateStreamSelectedCourse)
英文:
/_$/g,''
should be what you need :
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
let updateStreamSelectedCourse = 'mech (electronics)'.replace( /([^\w]+)/g, '_', ).replace(/_$/g,'');
console.log(updateStreamSelectedCourse)
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论