0

Hi for the below javascript I want a regex which will replace all instances of left square bracket with \Left square bracket ,right square bracket with \ plus right square bracket or full stop with a \ dot

<script type="text/javascript" type="text/javascript">

        $(document).ready(function () {
            var someId = '#Something[0].AnotherSelected[5].Validator';

            alert(s);
        });

    </script>
2
  • Your description of what you want doesn't match your example. You don't want to replace those characters with double slash, you want to prefix them with double slash. Commented Aug 1, 2012 at 10:46
  • your right barmar i have updated question to match. I want a regex which will replace all instances of left square bracket with \\Left square bracket ,right square bracket with \\ right square bracket or full stop with a \\ dot Commented Aug 1, 2012 at 10:49

4 Answers 4

3
var str = 'something[.something]].something[';
console.log(str.replace(/[\[\]\.]/g, '\\\\'));

Outputs

something\\\\something\\\\\\something\\';

[EDIT - based on the OP's comment below:

console.log(str.replace(/[\[\]\.]/g, function($0) { return '\\\\'+$0; }))
Sign up to request clarification or add additional context in comments.

1 Comment

thats close but i want to keep the square brackets but just put a \\ in front of it so i want str= #Something\[0\].AnotherSelected\[5\]\\.Validator
2

First we need a regular expression that matches '[',']' and '.' globally.
This regular expression looks like this:

 /(\[|\]|\.)/g

Then we replace each occurence with \\ concatenated with matched substring $&

var someId  = "#Something[0].AnotherSelected[5].Validator";
var newstr  = someId.replace(/(\[|\]|\.)/g, "\\\\$&")
alert(newstr)​

The output is

 #Something\\[0\\]\\.AnotherSelected\\[5\\]\\.Validator 

You can test it on jsfiddle

Comments

0
someId = someId.replace(/\[/g, "\\\\[").replace(/\./g, "\\\\.");

2 Comments

That's an invalid regular expression.
of course, but stackoverflow didn't display all my characters. So I've edited it.
0
someId = someId.replace(/[][.]/g, '\\\\$&');

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.