简体   繁体   中英

How to find symbols on a page and get a values between the two symbols in JS?

Some page have inserted secret text and JS script on this page should get a value between two characters, for example, between characters @@. In this variant @@569076@@ - 569076 should receive.

Here is what i've tried:

<div id="textDiv"></div>
<script>
    var markup = document.documentElement.outerHTML;
    var div = document.getElementById("textDiv");
    div.textContent = markup.match(/@@([^@]*)@@/);
    var text = div.textContent;
</script> 

But nothing displayed

you should put your text/code into a variable. You can replace body selector by yours.

Plain JS:

var html = document.getElementsByTagName('body')[0].innerHtml,
    match = html.match(/@@(\d+)@@/),
    digits;

if (match) {
    digits = match[1];
}

if you are using jQuery and like shortands:

var digits, match;

if (match = $('body').html().match(/@@(\d+)@@/)) {
    digits = match[1];
}

The problem is that the match function returns an array of matched values and textContent will only accept a string.

So you have to select which array item you want to use for the textContent assignment:

div.textContent = markup.match(/@@(\d+)@@/)[1];

Note we selected the first captured item using the [1] from the matches array.

If the string has spaces in, just add a space in the list of matched items like so:

var markup =  '@@56 90 76@@';
alert( markup.match(/@@([\d ]*)@@/)[1]);

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