JJ2357
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.
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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
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).
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">
:-)
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:
KR
Rainer
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(":","*"));
I updated the fiddle as well.KR
Rainer
ASKER
terrific, my bad. Thanks.
I'm adding here the code just for reference:
Open in new window