Navin Harish K
Navin Harish K

Reputation: 93

Regex to get word started with # in javascript

I have a problem replace certain words started with #. I have the following code

var x="#google",
eval("var pattern = /" + '\\b' + x + '\\b');
txt.replace(pattern,"MyNewWord");

when I use the following code it works fine

var x="google",
eval("var pattern = /" + '\\b' + x + '\\b');
txt.replace(pattern,"MyNewWord");

it works fine

any suggestion how to make the first part of code working

ps. I use eval because x will be a user input.

Upvotes: 2

Views: 138

Answers (4)

ruakh
ruakh

Reputation: 183270

The problem is that \b represents a boundary between a "word" character (letter, digit, or underscore) and a "non-word" character (anything else). # is a non-word character, so \b# means "a # that is preceded by a word character" — which is not at all what you want. If anything, you want something more like \B#; \B is a non-boundary, so \B# means "a # that is not preceded by a word character".

I'm guessing that you want your words to be separated by whitespace, instead of by a programming-language concept of what makes something a "word" character or a "non-word" character; for that, you could write:

var x = '#google';    // or 'google'
var pattern = new RegExp('(^|\\s)' + x);
var result = txt.replace(pattern, '$1' + 'MyNewWord');

Edited to add: If x is really supposed to be a literal string, not a regex at all, then you should "quote" all of the special characters in it, with a backslash. You can do that by writing this:

var x = '#google';  // or 'google' or '$google' or whatever
var quotedX = x.replace(/[^\w\s]/g, '\\$&');
var pattern = new RegExp('(^|\\s)' + quotedX);
var result = txt.replace(pattern, '$1' + 'MyNewWord');

Upvotes: 1

Ta Duy Anh
Ta Duy Anh

Reputation: 1488

If you want to make a Regular Expression, try this instead of eval:

var pattern = new RegExp(x);

Btw the line:

eval("var pattern = /" + '\\b' + x + '\\b');

will make an error because of no enclose pattern, should be :

eval("var pattern = /" + '\\b' + x + '\\b/');

Upvotes: 1

Steve
Steve

Reputation: 3046

How about

var x = "#google";

x.match(/^\#/);

Upvotes: 0

Inm0r74L
Inm0r74L

Reputation: 205

Make you patter something like this:

/(#)?\w*/

Upvotes: 1

Related Questions