代码之家  ›  专栏  ›  技术社区  ›  redoc01

如何使用javascript regexp替换字符串的一部分

  •  0
  • redoc01  · 技术社区  · 4 年前

    我有一个文本需要替换css的宽度部分:

    oldStyle = "width:90%;height:inherit;padding-right: 15px;padding-left: 15px;margin-right: auto;margin-left: auto;"
    

    我有这样的代码表达式或模式:

    oldStyle.replace(new RegExp("width:[0-9]+%;.*$", "g"), "width:25%;")
    

    但结果是:

    "width:25%;"
    

    它缺少css的其他部分:

    "height:inherit;padding-right: 15px;padding-left: 15px;margin-right: auto;margin-left: auto;"
    

    结果应该是:

    "width:25%;height:inherit;padding-right: 15px;padding-left: 15px;margin-right: auto;margin-left: auto;"
    

    如何只更改css的宽度部分,而保持其他css的完整性?

    4 回复  |  直到 4 年前
        1
  •  1
  •   Community Egal    4 年前

    此任务不需要使用正则表达式。还有更简单的选择。

    基本字符串操作

    function changeWidth(style, newValue) {
      const segments = style
        .slice(0, -1) //remove last `;`
        .split(';');
        
      const nonWidthSegments = segments.filter(segment => !segment.startsWith("width"));
      
      return nonWidthSegments
        .concat(`width: ${newValue}`)
        .join(';')
        .concat(';'); //add the last `;`
    }
    
    console.log(changeWidth(
      "width:90%;height:inherit;padding-right: 15px;padding-left: 15px;margin-right: auto;margin-left: auto;",  
      "45px"
    ));
    
    
    console.log(changeWidth(
      "margin: auto;",  
      "45px"
    ));
    
    
    console.log(changeWidth(
      "",  
      "45px"
    ));

    DOM操作

    function changeWidth(style, newValue) {
      const el = document.createElement("div");
      
      el.setAttribute("style", style);
      
      el.style.width = newValue;
      
      return el.getAttribute("style");
    }
    
    console.log(changeWidth(
      "width:90%;height:inherit;padding-right: 15px;padding-left: 15px;margin-right: auto;margin-left: auto;",  
      "45px"
    ));
    
    console.log(changeWidth(
      "margin: auto;",  
      "45px"
    ));
    
    console.log(changeWidth(
      "",  
      "45px"
    ));

    只是想更新VLAZ建议的答案,在进行了更多测试之后,这段代码实际上失败了 .startsWith 函数,因为假设您想要更改 border-bottom-left-radius 而正在经历的旧风格有一种旧的 border-bottom ,那么这个就会过滤掉 边界底部 而不是添加或更新 边框左下半径 .

    因此,我根据VLAZ的建议,对函数进行了一些修改: 传递的键是style属性,例如 border border-top width 或任何其他风格的属性。

    只是进一步编辑为 newStyle 我没有通过 newValue .

    function changeWidth(oldStyle, newValue, key) {
    
    const segments = oldStyle
            .slice(0, -1) //remove last `;`
            .split(';');
        
        var matchSegement = "";
        for (var t = 0; t < segments.length; t++) {
            if (segments[t].split(":")[0] == key) {
                matchSegement = segments[t];
            }
        }
    
        var nonWidthSegments = segments.filter(function (segment) {
            return segment != matchSegement;
        });
    
        var newStyle = nonWidthSegments
            .concat(key + `:${newValue}`)
            .join(';')
            .concat(';'); 
    
    }
    
        2
  •  1
  •   Mwase    4 年前

    你可以使用下面的正则表达式实现你想要的。正则表达式将用 % px rem 以及许多其他单位;

    string = "width:90%;height:inherit;padding-right: 15px;padding-left: 15px;margin-right: auto;margin-left: auto;"
    console.log(string.replace(/width ?: ?[0-9]+(%|[a-z]+|);/ig,"width:25%;"))
        3
  •  1
  •   Ahmet Zeybek    4 年前

    这将更改以开头的任何值 width %; 在字符串中,可以根据需要修改regexp

    first = "width:90%;height:100%;padding-right: 15px;padding-left: 15px;margin-right: auto;margin-left: auto;"
    second = "width:90%;height:inherit;padding-right: 15px;padding-left: 15px;margin-right: auto;margin-left: auto;"
    third = "height:inherit;padding-right: 15px;padding-left: 15px;width:90%;margin-right: auto;margin-left: auto;"
    
    console.log(first.replace(/width(.*?);/g,"width:25%;"))
    console.log(second.replace(/width(.*?);/g,"width:25%;"))
    console.log(third.replace(/width(.*?);/g,"width:25%;"))
        4
  •  1
  •   Md. Amirozzaman    4 年前

    只替换数值 width:90px; width:40px;

    width:90%; width:40%;

    str = "max-width:40px;width:90px;height:inherit;padding-right: 15px;padding-left: 15px;margin-right: auto;margin-left: auto;"
    console.log(str.replace(/([^-]width)(:[0-9]\d+)(.*)/g,"$1:25$3"))
    
    str = "max-width:40px;width:90%;height:inherit;padding-right: 15px;padding-left: 15px;margin-right: auto;margin-left: auto;"
    console.log(str.replace(/([^-]width)(:[0-9]\d+)(.*)/g,"$1:25$3"))
        5
  •  1
  •   Igor Bykov    4 年前

    这部分 width:[0-9]+%; 将在百分比中找到一些宽度值,但这部分 .*$ “匹配” 不管是什么直到绳子的尽头 ".

    但你不想让第二部分被 width:25%; ,所以,放下它:

    oldStyle.replace(new RegExp("width:[0-9]+%;", "g"), "width:25%;")
    

    这个RegExp肯定会有所改进。例如,正如人们在评论中正确指出的那样,它也会匹配 max-width:75% 然后将其更改为 max-width:25% . 然而,根据您的用例,它可能已经足够好了。

    一般来说,考虑到可能出错的事情的数量,在没有其他选择之前,您希望在这种情况下避免使用RegExp。