简体   繁体   中英

How to connect javascript var with text?

How to connect javascript var xx with /\\ and \\b/ ?

https://jsfiddle.net/6r4o5278/6/

<div onclick="check()">CLICK HERE</div>

<script>
  function check() {
    var str = "abcdefg";
    var xx = "abc";
    if (/\+xx+\b/.test(str)) 
    {
      alert("found");
    } else 
    {
      alert("not found");
    }
  }
</script>

Declare your regex before testing.

....
var xx = /abc\b/;
if (xx.test(str)) {
...

Note that this will not match the string "abcdefg" because \\b is a Word Boundary flag.

What do you mean by 'connect javascript var xx with /\\ and \\b/'. Furthermore see:

http://www.w3schools.com/jsref/jsref_regexp_test.asp

// The string:
var str = "Hello world!";

// Look for "Hello"
var patt = /Hello/g;
var result = patt.test(str);

// Look for "W3Schools"
patt2 = /W3Schools/g;
result2 = patt2.test(str);

use this one surely work...:)

var test = '/\\' + xx + '\\b/';
console.log(test);

it will be /\\abc\\b/.

Try to construct the expression this way:

 <script> function check(value) { var str = "abcdefg"; var re = new RegExp(value); var found = str.match(re); if (found) { console.log(value + " - found"); } else { console.log(value + " - not found"); } } check('xsxsd'); check('abc'); check('refer'); check('cde'); </script> 

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