Alexander
Alexander

Reputation: 2463

Converting php regexp to JavaScript

I'm trying to convert the following php expression into JavaScript but I'm having trouble with one thing.

preg_replace('/'.preg_quote($keyword).'/i', "<span>$0</span>", $string)

What happens here is that I can reuse the found substring with the right "case letters". Its hard to explain what I mean but let me give an example:

If the user inputs sweden, then this string is all lowercase letters. But in the result this same word is written as Sweden, so I want it to keep its cases as they are.

it is possible to do this in php by using the matched value $0, as you can see in the php expression.

In JavaScript what I have so far is:

var highlighted_sub = location_sub_name[i].replace(regexp_highlight,"<span class='loc_keyword'>" + location_keyword + "</span>");

This replaces the original result with the input from the user, so I get sweden in all lower case letters as the user input them, when I actually want the cases to be as they really are.

Upvotes: 0

Views: 94

Answers (1)

tdammers
tdammers

Reputation: 20721

You can do the same in javascript; the only exception is that the "entire match" backreference is $& instead of $0. The rest, $1 through $9, works exactly the same though. Try it out in the address bar of your browser:

javascript: document.write('foobar'.replace(/(f)[o]/g, ' $1 $& '));

This page has more info: http://www.regular-expressions.info/refreplace.html

Upvotes: 1

Related Questions