【问题标题】:javascript string replace with another valuejavascript字符串替换为另一个值
【发布时间】:2011-11-12 07:38:27
【问题描述】:

你好,

var s = "width:20px;height:25px;color:red;font-family:myfontfamily";

我有一个这样的字符串,现在我如何使用 javascript 更改宽度、高度等的值。在属性(宽度、高度等)之后或之前可能有一个 \n..

例如:我想在s 上将width 更改为50px。 所以会是

var s = "width:50px;height:25px;color:red;font-family:myfontfamily";

我的另一个问题在这里Regular Expression to get text from css,但它不能完全满足我的需要。

请帮帮我。

谢谢。

Update : You can see the Result on my fiddle here : http://jsfiddle.net/jitheshkt/s2DJR/14/

【问题讨论】:

  • 嗨。与其直接使用 CSS 字符串,不如使用 js 内置样式的修饰符?喜欢document.getElementById('thing').style.width = '50px';
  • 字符串 s 来自编辑器,而不是来自网页,我也想将数据返回到该编辑器。这也不是 dom 对象,只是字符串。

标签: javascript regex string replace


【解决方案1】:

正则表达式。

例如:

s = s.replace(/color:\s*([^;]+)/, "color:" + newvalue)

【讨论】:

  • 效果很好,但我有一个自定义值,即background:url({background}) 代码中断...有什么办法可以避免这种情况...
  • 嗨,检查一下这个var s = "background-color:white;color:red;" s = s.replace(/color:\s*([^;]+)/, "color:" + 'green'); alert(s); 它替换了background-color 值...有没有办法覆盖这个?
【解决方案2】:
var s = "width:20px;\nheight:25px;\ncolor:red;\nfont-family:myfontfamily";

alert( s.replace(/width:\d+/,'width:123').replace(/height:\d+/,'height:456') );

【讨论】:

  • 谢谢,但只能使用 int 值,我无法更改颜色值。
猜你喜欢
  • 2016-02-21
  • 2013-12-31
  • 1970-01-01
  • 2013-12-03
  • 2019-05-14
  • 2023-04-03
  • 2011-12-21
  • 1970-01-01
  • 2012-07-16
相关资源
最近更新 更多