Remove a semicolon in a string by JavaScript

This question already has an answer here:

  • How to replace all occurrences of a string in JavaScript? 41 answers

  • You can use the replace method of the string object. Here is what W3Schools says about it: JavaScript replace().

    In your case you could do something like the following:

    str = str.replace(";", "");
    

    You can also use a regular expression:

    str = str.replace(/;/g, "");
    

    This will replace all semicolons globally. If you wish to replace just the first instance you would remove the g from the first parameter.


    Try this:

    str = str.replace(/;/g, "");
    

    This will remove all semicolons in str and assign the result back to str .


    Depending upon exactly why you need to do this, you need to be cautious of edge cases:

    For instance, what if your string is this (contains two semicolons):

    '<div id="confirmMsg" style="margin-top: -5px; margin-bottom: 5px;">'
    

    Any solution like

     str.replace(";", "");
    

    will give you:

    '<div id="confirmMsg" style="margin-top: -5px margin-bottom: 5px">'
    

    which is invalid.

    In this situation you're better off doing this:

     str.replace(";"", """);
    

    which will only replace ;" at the end of the style string.

    In addition I wouldn't worry about removing it anyway. It shouldn't matter - unless you have already determined that for your situation it does matter for some obscure reason. It's more likely to lead to hard-to-debug problems later if you try to get too clever in a situation like this.

    链接地址: http://www.djcxy.com/p/16834.html

    上一篇: Javascript replaceAll不工作

    下一篇: 通过JavaScript删除字符串中的分号