Nik Sumeiko
Nik Sumeiko

Reputation: 8723

Regex to find specific dots and escape them

I have a string "#letme.doit.now .emiter #another.test #plus.test." I need to find all dots that has something after, which are in those parts that starts with # and don't have white spaces. Actually the match has to hold dot 1, 2, 4 and 5. All other dots don't have to be there in the match.

Upvotes: 0

Views: 697

Answers (2)

Rezigned
Rezigned

Reputation: 4932

This is what you want.

For matching

"#letme.doit.now .emiter #another.test #plus.test.".match(/#[a-zA-Z0-9]+(\.\w+)+/g)

Will return ["#letme.doit.now", "#another.test", "#plus.test"]

For escape

"#letme.doit.now .emiter #another.test #plus.test.".replace(/(#[a-zA-Z0-9]+)\.(\w)/g, '$1\\.$2')

Upvotes: 0

Rob W
Rob W

Reputation: 349012

This will find and escape the dots according to the requirements:

Demo: http://jsfiddle.net/q9hLQ/

var string = "#letme.doit.now .emiter #another.test #plus.test.";
string = string.replace(/#\S+/g, function(full_match) {
    return full_match.replace(/\.(?!$)/g, '\\.');
});
// Output: #letme\.doit\.now .emiter #another\.test #plus\.test.
  1. Find each consecutive # + non-whitespace characters.
  2. Inside these matches, replace all dots, except for the dot at the end, with a backslash+dot.

Upvotes: 3

Related Questions