正则表达式函数未通过测试。

huangapple go评论97阅读模式
英文:

regEx function not does not pass test

问题

Sure, here are the translated parts of your content:

Just wondering what could be wrong with my regEx function, is returning false, is there a better or cleaner approach to mimic startsWith as my application has an embedded JS engine that is ecma 1.8.5 spidermonkey

function startsWith(i, s) {
  var regEx = new RegExp("^" + i + "/");
  console.log(regEx)
  return regEx.test(s);
}

const myString = "hello world";

console.log(startsWith("hello", myString));

update
Is failing to test when special characters in strings also.

startsWith("%^&.h", myString)

Please note that the code itself remains unchanged, and I have provided the translated text as requested.

英文:

Just wondering what could be wrong with my regEx function, is returning false, is there a better or cleaner approach to mimic startsWith as my application has an embedded JS engine that is ecma 1.8.5 spidermonkey

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

function startsWith(i,s) {
  var regEx = new RegExp(&quot;/^&quot;+i+&quot;/&quot;);
  console.log(regEx)
  return regEx.test(s);
}


const myString = &quot;hello world&quot;;

console.log(startsWith(&quot;hello&quot;,myString));

<!-- end snippet -->

update
Is failing to test when special characters in strings also.

> startsWith("%^&.h",myString)

答案1

得分: 2

有一种更简单的方法可以在不使用正则表达式的情况下实现这一目标:

function startsWith(i, s) {
  return s.indexOf(i) === 0;
}

const myString = "hello world";

console.log(startsWith("hello", myString));

请注意,上述代码片段已经在JavaScript中提供。

英文:

There is a much simpler way to achieve this without regex:

<!-- begin snippet: js hide: false console: true babel: null -->

<!-- language: lang-js -->

function startsWith(i,s) {
  return s.indexOf(i) === 0;
}

const myString = &quot;hello world&quot;;

console.log(startsWith(&quot;hello&quot;,myString));

<!-- end snippet -->

答案2

得分: 2

这是已经更正的startsWith函数:

function startsWith(i, s) {
  var regEx = new RegExp("^" + i);
  return regEx.test(s);
}
英文:

Here's the corrected startsWith function:

function startsWith(i, s) {
  var regEx = new RegExp(&quot;^&quot; + i);
  return regEx.test(s);
}

huangapple
  • 本文由 发表于 2023年3月7日 04:37:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/75655597.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定