Link to home
Start Free TrialLog in
Avatar of JJ2357
JJ2357Flag for United States of America

asked on

Find & Replace same characters in within different elements

I have several different form labels, each with a unique "for" attribute.  I want to replace a text string that occurs within the values of only those labels with select "for" attirbutes. For example, suppose I want to replace replace  ":" with "*" within the text in all labels where for is lorem or ipsum.

This:
<label for="lorem">LOREM:  </label>
<label for ="ipsum">IPSUM:  </label>
<label for ="dolor">DOLOR:  </label>

Becomes this:
<label for="lorem">LOREM*  </label>
<label for ="ipsum">IPSUM*  </label>
<label for ="dolor">DOLOR: </label>

I'd like to use jquery or plan javascript.

Thanks.
ASKER CERTIFIED SOLUTION
Avatar of Rainer Jeschor
Rainer Jeschor
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Here's a sample fiddle: Sample

I'm adding here the code just for reference:
var forArray = ['lorem', 'ipsum'],     // specify the 'for' values here
    replace = { src: ':', dest: '*' }; // specify the replace settings here

for(var i=0; i<forArray.length; i++){
    var elements = $('label[for="' + forArray[i] + '"]');
    for(var j=0; j<elements.length; j++){
        var $elem = $(elements[j]),
            elemHtml = $elem.html();

        $elem.html(elemHtml.replace(replace.src, replace.dest));
    }
}

Open in new window

Avatar of JJ2357

ASKER

@Rainer - thanks.  The solution works as requested.  Do you know if there's any way to just replace just the first instance of ":" within the label?  I ask because some of the label values include URL's, and the ":" is getting stripped from those too.
Hi,
thanks for the points.
The replace function by default will only replace the first instance - I have just updated the jsFiddle (same url as above).
As you can see, only the first one gets replaced.
KR
Rainer
At least in Chrome and IE11 (just tested).
Avatar of JJ2357

ASKER

Interesting.  It only  happens when the ":" is included within a tag.  Example: replace the URL in your updated fiddle with:
<img src="https://www.google.com/images/srpr/logo11w.png">

Open in new window

:-)
Your sample did just contain plain text - so no additional tags. Therefore I used the text() function.
If your label contains html then we have to use the html() function:
$(this).html($(this).html().replace(":","*"));

Open in new window

I updated the fiddle as well.
KR
Rainer
Avatar of JJ2357

ASKER

terrific, my bad.  Thanks.