简体   繁体   中英

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. 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. 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. 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.

Split your string into a char array, then replace your desired 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 . 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 . The 0 is replaced with 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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