简体   繁体   English

如何只用一个空格替换字符串字符?

[英]How to replace string characters with only one blank space?

I'm trying to replace all "WUB" in a string with a blank space. 我正在尝试用空格替换字符串中的所有“ WUB”。 The problem is, if I have 2 "WUB" in a row, it will return 2 blank spaces. 问题是,如果我连续有2个“ WUB”,它将返回2个空格。 How do only return 1 blank space if I have "WUBWUB"? 如果我有“ WUBWUB”,怎么只返回1个空格?

function songDecoder(song) {
    var replacedLyrics = song.replace(/#|WUB/g,' ');
    return replacedLyrics;
}

Try this regex /(WUB)+/g it will match 1 or more element in the parenthesis 试试这个正则表达式/(WUB)+/g ,它将匹配括号中的1个或多个元素

 function songDecoder(song) { var replacedLyrics = song.replace(/(WUB)+/g,' '); return (replacedLyrics); } console.log(songDecoder("hello world !")); console.log(songDecoder("WUB")); console.log(songDecoder("helloWUBWUBworldWUB!")); 

/#|WUB/g should be /#|(WUB)+/g for your purpose. /#|WUB/g应该是/#|(WUB)+/g Do you also want to replace multiple "#"s with a single space. 您是否还想用一个空格替换多个“#”。 Then you might want /(#|WUB)+/g 然后,您可能需要/(#|WUB)+/g

The parentheses group the target strings together, then plus seeks one or more repetition of the group. 括号将目标字符串分组在一起,然后加号寻求该组的一个或多个重复。

If you don't want a space at the beginning or end of your string, that could be another regex function, but probably the most straightforward method is to use the .trim() function. 如果您不希望在字符串的开头或结尾使用空格,则可以使用另一个正则表达式函数,但最直接的方法可能是使用.trim()函数。 So: 所以:

 alert( songDecoder('WUBYOUREWUBWELCOMEWUB') ) function songDecoder(song) { var replacedLyrics = song.replace(/(#|WUB)+/g,' ').trim(); return replacedLyrics; } 

Change your code to .replace(/#|(WUB)+/g, " "); 将您的代码更改为.replace(/#|(WUB)+/g, " "); .

This searches for as many "WUB's" in a row before replacing them with a blank space 这将连续搜索“ WUB”,然后用空格替换它们

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM