【问题标题】:RegEx for replacing a specific word用于替换特定单词的正则表达式
【发布时间】:2019-10-24 04:27:40
【问题描述】:

我正在尝试将背景颜色更改为一个特定的单词以使用正则表达式,但我不知道如何在 javascript 中编写此代码

我尝试编写一些javascript代码,但没有成功

let test = RegExp(/\bjavascript/ig).css('background-color' 'blue');

我重新加载页面,但它不起作用。

【问题讨论】:

  • 你的意思是改变一个html元素的背景颜色吗?为什么要使用正则表达式?

标签: javascript css regex regex-group


【解决方案1】:

我猜我们想捕获和更改 CSS 格式的颜色,我们可以使用类似于以下的表达式:

(background(-color)?):\s+(.+?)(\s+)?;

Demo 1

或:

(background-color):\s+(.+?)(\s+)?;

Demo 2

测试

const regex = /(background(-color)?):\s+(.+?)(\s+)?;/gmi;
const str = `background-color: blue;
background: green;
background: green ;
background: green ;`;
const subst = `$1:yellow;`;

// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);

console.log(result);

正则表达式电路

jex.im 可视化正则表达式:

【讨论】:

    猜你喜欢
    • 2018-08-30
    • 2021-08-05
    • 1970-01-01
    • 2019-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-10
    • 1970-01-01
    相关资源
    最近更新 更多