Marvin3
Marvin3

Reputation: 6041

Replace words that start from underscore

I have a block of text and each word in it, that starts from underscore should be replaced with another unique string.

For example:

_word -> _a 
_anotherword -> _b
_another_word -> _c
._dotwithword -> ._d
[_brword] -> [_e]
another_word -> another_word (should stay the same)

I'm using this regex to find them - (_\w+) , and it replaces everything correctly, except the last one if underscore is in the middle of the word. Is there any way to check this via JS regex?

JS fiddle to test: http://jsfiddle.net/C93bs/3/

Thanks a lot!

Upvotes: 2

Views: 527

Answers (3)

fredrik
fredrik

Reputation: 17617

Maybe not the nicest solution but it should work:

/((^|\s)[\,\[\.]?_\w+(\])?)/g

Updated jsfiddle

EDIT: Beyamor solution is much cleaner

Upvotes: 0

Beyamor
Beyamor

Reputation: 3378

(\b_\w+) - \b matches on a word boundary.

Upvotes: 6

Bob Davies
Bob Davies

Reputation: 2282

Complete regexp (works in your fiddle):

/\b(_\w+)\b/g

Upvotes: 3

Related Questions