user1148809
user1148809

Reputation:

Replacing regex match in JavaScript

I am using JavaScript's replace() function to replace a regular expression matching A-Z, a-z, 0-9, dash (-), underscore (_) and dot (.). I am trying to replace it with part of the matched string with tags around it, but the code I have only replaces the matches with: <b>$1</b>.

Any help, please?

<!DOCTYPE html>
<html>
<body>

<textarea id="demo" rows="10" cols="20">
<table></table>
<b><i>#stock-jsod.20</i>
</b>
</textarea>

<button onclick="testit()">test</button>

<script type="text/javascript">

function testit()
{
var str=document.getElementById("demo").value;
var n = str.replace(/#([A-Za-z0-9_.-]+)/gi, "<b>$0</b>");
document.getElementById("demo").innerHTML=n;
}
</script>

</body>
</html>

My goal here is to replace #stock-jsod.20 with <b>#stock-jsod.20</b>, but currently it only replaces it with <b>$0</b>.

Upvotes: 2

Views: 608

Answers (2)

Mark Byers
Mark Byers

Reputation: 838216

In addition to Engineer's answer you also don't the A-Za-z0-9_. You can just use \w. Then you also don't need the case insensitive switch. This is a much simpler regular expression that achieves the same effect:

var n = str.replace(/#[\w.-]+/g, "<b>$&</b>");

Example output:

> str = '#abc #def ghi'
"#abc #def ghi"
> str.replace(/#[\w.-]+/g, "<b>$&</b>");
"<b>#abc</b> <b>#def</b> ghi"

Upvotes: 1

Engineer
Engineer

Reputation: 48793

Try to use '$&' instead of '$1'.

More about look -> https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/replace#Description

UPDATE: Instead of document.getElementById("demo").value you need to use document.getElementById("demo").innerHTML for getting contents of 'demo' element.

Upvotes: 2

Related Questions