-2

.replace(/rgba(0,0,0,0.87)/g,newPrimaryTextColor)

Is not working. Have any other option?

I am trying to get replace old css with new css via jquery. CSS file get via jquery.

  • What you have put there as your "code" could be understood as a fragment that uses the String method `replace()`. But it is completely unclear what object (the thing before the `.`) you are applying this to ... So far the question shows no reference to jquery. Please try and explain (in your post) in a bit more detail, *what you are trying to achieve* and how you want this piece of code to interact with your page. – Carsten Massmann Apr 03 '17 at 13:46

2 Answers2

0

If you are looking for a way to replace an existing text color definition by a new one then maybe the following might help you:

$('span').filter(function() {   // span,div,td ... or other desired elements
    var match = 'rgb(0, 0, 0)'; // match text-color: black
    /*
        true = keep this element in our wrapped set
        false = remove this element from our wrapped set
    */
    return ( $(this).css('color') == match );

}).css('color', newPrimaryTextColor); // actually change the color

This is an adaptation of a previous question Selecting elements with a certain background color and it will only change those elements with an explicit color definition of rgb(0, 0, 0) on it. A better approach might be to work with classes instead, but I can only guess ...

Community
  • 1
  • 1
Carsten Massmann
  • 26,510
  • 2
  • 22
  • 43
0

The issue is the regular expression is failing to escape the (starting and ending of the string ). You need to add separate logic to escape these characters:

    function escapeSpecialChars(s) {
    return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
    }

Now specify your method as specified below:

    function ReplaceColor() {
    var textContent = "Replace rgba(0,0,0,0.87) with red";
    var expression = new RegExp(escapeSpecialChars("rgba(0,0,0,0.87)"));
    var res = textContent.replace(expression, 'red');
    }

Please refer Is there a RegExp.escape function in Javascript? for more details

Community
  • 1
  • 1