2

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>.

asked Jun 24, 2012 at 18:38
1
  • 1
    There is already a <b></b> around it! Commented Jun 24, 2012 at 18:47

2 Answers 2

2

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.

answered Jun 24, 2012 at 18:41

Comments

1

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"
answered Jun 24, 2012 at 18:41

2 Comments

@JoshuaShor: What do you mean by "does not work". I've tested it and it appears to work - see the example output. Are you sure that the problem you have is not elsewhere? What is the error you get?
Yeah, @JoshuaShor has strange sense of humour !!

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.