简体   繁体   English

如何替换字符串中用字母字符括起来的数字字符

[英]How to replace a numeric character enclosed by alphabetic characters in a string

I have a very, very long string containing words like mushr0om , mong0lian , c0rn , etc. I want to replace the 0 's with o 's. 我有一个非常长的字符串,其中包含mushr0ommong0lianc0rnc0rn 。我想将0替换为o I know that input.replace('0', 'o') may work, but in the very same string it also contains numbers like 70 , 100 , 1082 , and I don't want the replace method to affect them. 我知道input.replace('0', 'o')可以工作,但在非常相同的字符串时,它也含有相同的数字701001082 ,我不希望replace的方法来影响他们。 Can I use regular expressions to do this? 我可以使用正则表达式来做到这一点吗?

 var string = "mushr0om 70 bl00m 102" var cleanString = string.split(' ').map((word)=>{ if(! /^\\d+$/.test(word) ){ return word.replace(/0/g,'o')} return word }).join(' ') console.log(cleanString); 

You can check (previous and next character) for each character. 您可以检查(上一个和下一个字符)每个字符。 If a character is a digit then check whether it's prev. 如果字符是数字,请检查其是否为上一个字符。 or next character is a non digit. 或下一个字符为非数字。 If any of the prev. 如果有的话。 or next character is a non digit then replace. 或下一个字符为非数字,然后替换。

  • But if you have any substring like 'mongolia007' in your desired string set then the solution gets tricky. 但是,如果在所需的字符串集中有诸如“ mongolia007”之类的子字符串,则解决方案会很棘手。 But for simple case above solution should work. 但对于简单的情况,上述解决方案应该有效。

I think you want to replace all '0' which previous letter not a number and also the next letter not a number. 我认为您想替换所有的“ 0”,即前一个字母不是数字,而下一个字母不是数字。

Split your string into a char array, then replace your desired char. 将您的字符串拆分为一个char数组,然后替换您想要的char。

var str = 'Twas th0e ni0ght befo100re Xm305as...';
var char = str.split('');
for(var i=0; i<str.length; i++){
    if((i==0 || char[i] != " ") && ! isNaN(char[i]) && isNaN(char[i+1]))
        char[i] = 'o';
    else if(isNaN(char[i-1]) && ! isNaN(char[i]) && (char[i] != " " || i+1 == str.length))
        char[i] = 'o';        
    else if(isNaN(char[i-1]) && ! isNaN(char[i]) && char[i] != " " && isNaN(char[i+1]))
        char[i] = 'o';

    document.getElementById("demo").innerHTML = document.getElementById("demo").innerHTML + char[i];
}

If I understand, you only need to replace the 0 occurring between characters and not the 0 in actual figure like 900 . 据我了解,您只需要替换字符之间出现的0而不是实际数字中的0 ,例如900 Below regular expression creates three groups, two for characters and a zero sandwiched between them. 在正则表达式下方创建了三个组,两个用于字符,而零则夹在它们之间。 Then we pick the first group (character before 0) using $1 and second (after 0) with $3 . 然后我们选择第一组(字符0之前)使用$1和第二(0之后)与$3 The 0 is replaced with o . 0替换为o

 var str = "mushr0om, mong0lian, c0rn - 700 hello909"; var str1 = str.replace(/([a-zA-Z])(0)([a-zA-Z])/ig, "$1o$3"); document.getElementById("dvOne").innerText = str1; 
 div { padding: 25px; color: red; font-size: 16px; } 
 <div id="dvOne"> </div> 

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

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