3 Replies - 355 Views - Last Post: 06 August 2012 - 02:30 PM

#1 satis  Icon User is offline

  • D.I.C Head

Reputation: 82
  • View blog
  • Posts: 231
  • Joined: 26-May 11

.replace regex not working

Posted 06 August 2012 - 08:08 AM

I must be making a simple mistake, but I can't get a .replace() with regex working. Here's a code example that works:

	var title = $(this.titleBlock).find('.title')[0];
		title.innerHTML = 'This is a test';
	var searchTerms = ['is', 'test'];
	for(var i in searchTerms){
		title.innerHTML = title.innerHTML.replace(searchTerms[i], '<span class="highlight">' + searchTerms[i] + '</span>');
	}



But if I try to turn the search into a regex, it doesn't work. I want to use regex for global and case insensitive replace:

	var title = $(this.titleBlock).find('.title')[0];
		title.innerHTML = 'This is a test';
	var searchTerms = ['is', 'test'];
	for(var i in searchTerms){
		title.innerHTML = title.innerHTML.replace(/searchTerms[i]/gi, '<span class="highlight">' + searchTerms[i] + '</span>');
	}



I get no errors, but nothing is replaced. Can anyone tell me what I'm doing wrong?

Is This A Good Question/Topic? 0
  • +

Replies To: .replace regex not working

#2 Atli  Icon User is online

  • D.I.C Lover
  • member icon

Reputation: 3039
  • View blog
  • Posts: 4,552
  • Joined: 08-June 10

Re: .replace regex not working

Posted 06 August 2012 - 09:01 AM

You can't define a dynamic expression that way. You'll have to use the RegExp object to create that kind of an expression.

var regexp = new RexExp(searchTerms[i], "gi");


Was This Post Helpful? 1
  • +
  • -

#3 satis  Icon User is offline

  • D.I.C Head

Reputation: 82
  • View blog
  • Posts: 231
  • Joined: 26-May 11

Re: .replace regex not working

Posted 06 August 2012 - 09:59 AM

Got it, thank you.

	for(var i in searchTerms){
		var regexp = new RegExp(searchTerms[i], 'gi');
		title.innerHTML = title.innerHTML.replace(regexp, '<span class="highlight">' + searchTerms[i] + '</span>');
	}


Now I need to dig into regex a bit so I don't end up replace strings inside html tags, but I can plug away at that on my own. I appreciate the speedy response.
Was This Post Helpful? 0
  • +
  • -

#4 Dormilich  Icon User is offline

  • 痛覚残留
  • member icon

Reputation: 2888
  • View blog
  • Posts: 7,535
  • Joined: 08-June 10

Re: .replace regex not working

Posted 06 August 2012 - 02:30 PM

Note: for…in is not supposed to be used on arrays (that would be a standard for loop). for…in is intended for looping over object properties.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1