非常初级,如果不合适,请见谅。
我试图用破折号替换字符串中的所有字母,如果它只有一个字符,我的代码就可以工作,但不能超过一个。我试过 for 循环,但也不起作用. 我一直在阅读其他主题,例如:Other thread但不知道我做错了什么,我已经读了一段时间了。 谁能帮帮我?
到目前为止,这是我的代码:
function replaceLettersWithDashes(str) {
/* This function will receive a string with a mix of characters. It should return the string with all letters replaced by dashes ('-').
For example 'You like cake' should return '--- ---- ----', and 'Tree 4, 6, 8' should return '---- 4, 6, 8'.
*/
return str.replace(/^[a-zA-Z]+$/g , '-');
}
提前致谢。
最佳答案
您可以搜索单个字母并将其替换为这个正则表达式,它会查找一个字母并将每个字母替换为破折号。标志 'g'
和 'i'
用于全局搜索和不区分大小写的搜索。
/[a-z]/gi
如果您使用 +
或 *
作为量词,您将获得所有后续字母并将其替换为单个破折号,这是不需要的。
function replaceLettersWithDashes(str) {
return str.replace(/[a-z]/gi , '-');
}
console.log(replaceLettersWithDashes('You like cake'));
console.log(replaceLettersWithDashes('Tree 4, 6, 8'));
关于javascript - 用破折号替换字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49458393/