简体   繁体   中英

Why am I getting a / in my regex output?

My untouched HTML looks like this:

<body class="home bc-hide-1bc-hide-2">

My JS looks like this:

var c = $("body").attr("class").replace(/(bc-hide-\d)/,/$& /);
$("body").attr("class", c);

The goal is to get my HTML to look like this (note the space between bc-hide-1 and bc-hide-2):

<body class="home bc-hide-1 bc-hide-2">

Using the JS above, my output actually ends up with a / in front of each instance of bc-hide-# (seen below):

<body class="home /bc-hide-1 /bc-hide-2">

I haven't had to do too much with regex and I have been poking around the documentation but I am just not finding what I need to stop that / from outputting. Any help is greatly appreciated!

Thanks!

To answer the actual question:

Why am I getting a / in my regex output?

Because you have two slashes in the replacement: /$& / .

The replacement should be a string, not a regular expression, and /$& /.toString() (the string representation of the expression) is "/$& /" .

Just use '$& ' .


But I agree with Evan, you should fix the code that generates the HTML.

var c = $("body").attr("class").replace(/(bc-hide-\d)/,'$& ');

The replacement is a string, not a regex. JS turned the regex you passed in into a string, including the slashes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM