1

I'm trying to sort out how to replace a substring in a string when the substring to be found/replaced is a variable that may have one or more occurrences of a forward slash. I suspect the issue is in escaping the incoming string properly....but I'm kind of lost on the syntax to insert the escapes correctly.

var incomingStr = 'some text/take / out/ and yet more.';
var removethis = '/take / out/';
newStr = incomingStr.replace(removethis," ");
newStr should be:  'some text and yet more.'
1
  • escape the forward slash using a backslash \/ Commented Mar 31, 2012 at 0:48

2 Answers 2

3

You can "quote" or "escape" it using a backslash:

var removethis = '/take \/ out/';

Or if you prefer, you can wrap it in a character class:

var removethis = '/take [/] out/';
Sign up to request clarification or add additional context in comments.

Comments

0

It does work! Here is an example on jsfiddle:

http://jsfiddle.net/pipalia/BdvZn/

<html>
    <head>
        <script language="javascript">
            function testStr() {
                var incomingStr = 'some text/take / out/ and yet more.';
                var removethis = '/take / out/';
                var newStr = incomingStr.replace(removethis,"");
                alert(newStr);
            }
        </script>
    </head>
    <body>
        <button onclick="testStr()">Click here</button>
    </body>
</html>​

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.