英文:
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("/^"+i+"/");
console.log(regEx)
return regEx.test(s);
}
const myString = "hello world";
console.log(startsWith("hello",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 = "hello world";
console.log(startsWith("hello",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("^" + i);
return regEx.test(s);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论