1

I am trying to write a regex that finds the space in between "Red" and "Blend" in the text of the link.

<a title="Show products matching tag Red Blend" href="/collections/50-to-100/red-blend">Red Blend</a>

The regex will also need to be able to find both of the spaces in the following block of code:

<a title="Show products matching tag Russian River Valley" href="/collections/50-to-100/russian-river-valley">Russian River Valley</a>

In both cases I am going to be replacing the space with a non-breaking space character, but that will be handled by my server-side script.

Thanks in advance for the help.

TrentonMcManus
  • 487
  • 1
  • 7
  • 16
  • So you want to capture all of the whitespace inside of the `title` attribute, after `Show products matching tag `? – cheeken Sep 19 '11 at 17:54
  • 4
    What environment are you working in? You shouldn't use regex for this, and chances are that you don't have to. – Tomalak Sep 19 '11 at 17:55
  • 5
    TO͇̹̺ͅƝ̴ȳ̳ TH̘Ë͖́̉ ͠P̯͍̭O̚​N̐Y̡ H̸̡̪̯ͨ͊̽̅̾̎Ȩ̬̩̾͛ͪ̈́̀́͘ ̶̧̨̱̹̭̯ͧ̾ͬC̷̙̲̝͖ͭ̏ͥͮ͟Oͮ͏̮̪̝͍M̲̖͊̒ͪͩͬ̚̚͜Ȇ̴̟̟͙̞ͩ͌͝S̨̥̫͎̭ͯ̿̔̀ͅ – Michael Jasper Sep 19 '11 at 17:58
  • This is actually going to be used in a shopify theme. Shopify theme symtax is based on Rails syntax, and there is a simple replace filter. [Here is a link to the shopify replace filter](http://wiki.shopify.com/Replace). I don't actually know if regex will work in shopify, so I was planning to do it in javascript as a backup. – TrentonMcManus Sep 19 '11 at 20:59
  • @cheeken No, I am looking for a way to remove the whitespace from the text of the link, not the `title` attribute. – TrentonMcManus Sep 19 '11 at 21:02
  • 2
    For those of you flagging @Michael 's comment because you don't get the "Tony the Pony" reference, see here: http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454 – Robert Harvey Sep 19 '11 at 22:46
  • @RobertHarvey Ok, thanks for clarifying the Tony the Pony part. I humbly accept my chastisement and vow not to ever try to parse html with regex. – TrentonMcManus Sep 20 '11 at 00:02

1 Answers1

2

Not sure what language you are using, but if you want to use a little javascript/jQuery, you could do this;

var a = $('a').text();
var b = a.replace(/\s/g, '&nbsp;');
$('a').html(b);

This assumes (from your question) that the space you want to replace is in the text of the link.

Example: http://jsfiddle.net/jasongennaro/ejJYF/1/

Jason Gennaro
  • 34,535
  • 8
  • 65
  • 86
  • 3
    If are using jQuery, at least use it *right*: `$('a').text(function(i, t) {return t.replace(/\s/g, String.fromCharCode(160)); });` – Tomalak Sep 19 '11 at 18:54
  • Nicely written @Tomalak. Learned something new – Jason Gennaro Sep 19 '11 at 19:12
  • 1
    @Tomalak Great job and thanks so much! Here is my test of Tomalak's jQuery function with a larger set of sample data: http://jsfiddle.net/ejJYF/2/ This should take care of my problem – TrentonMcManus Sep 19 '11 at 21:15