简体   繁体   中英

Getting Javascript Regular Expression from Page

I'm trying to grab a regular expression from an HTML element so that I can use it for evaluation later, but for some reason when I grab the RE from the DOM it's different than when I statically define it in my Javascript. Here is my testing code:

<p id="test">\\b31\\b</p>

<script>
var j = document.getElementById('test').innerHTML;
console.log(j);
var i = "\\b31\\b"
console.log(i);

</script>

The results of this are \\\\b31\\\\b for j and \\b31\\b for i. Why isn't j also \\b31\\b? More importantly, how do I fix this? Because my regular expression evaluation later won't work with j, and I need to be able to grab regular expressions from the page to evaluate later, but right now I can't unless I statically define them.

i don't know exactly why this is happening, but you could just simply fix this with:

var j = document.getElementById('test').innerHTML.replace(/\\\\/g,"\\");

see example here: https://jsfiddle.net/wjnm15gL/1/

You cannot "fix" this. By design, the backslash in JS is used to escape special characters, such as newlines (\\n). If you want to use a literal backslash, a double backslash has to be used.

If you want to use two backslashes, use four:

console.log('\\\\'); //returns \\

JavaScript strings automatically escape special characters following a \\ character. Try this in your console to see:

console.log('It\'s a wonderful day');
//It's a wonderful day

That's why your j and i variables log differently to the console.

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