javascript regex for eliminating punctuations array

Discussion in 'JavaScript' started by gilgalbiblewheel, Nov 6, 2008.

  1. #1
    I made an array of punctuation which I want to eliminate from the string:
    		/*to eliminate the punctuations*/
    		var punctuations = new Array();
    		punctuations[0] = ":";
    		punctuations[1] = ";";
    		punctuations[2] = ",";
    		punctuations[3] = ".";
    		punctuations[4] = "?";
    		punctuations[5] = "(";
    		punctuations[6] = ")";
    		var eliminate = "";
    		var myOldString = searchChapWords[i].innerHTML;
    		for(punct=0; punct<punctuations.length; punct++){
    			var myNewString = myOldString.replace(punctuations[punct], eliminate);
    		}
    		document.getElementById('keyword0').innerHTML = "Old string =  " + myOldString;
    		document.getElementById('keyword1').innerHTML = "<br />New string = " + myNewString
    		/*end*/
    Code (markup):
    What's the correct way of doing it?
     
    gilgalbiblewheel, Nov 6, 2008 IP
  2. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,999
    Best Answers:
    253
    Trophy Points:
    515
    #2
    This sounds like a job for a regular expression. I would replace your punctuations array, your eliminate string, and the for loop with this one line of code.

    var myNewString=myOldString.replace(/[:;,.?()]/g,'');
     
    deathshadow, Nov 7, 2008 IP