使用JavaScript,如果另一个字符串以第一个字符串开头,如何从其他字符串中删除字符串?
var matcher='Hello';
var s1='hello everyone';
console.log(someFunction(s1,matcher);
//Should return ' everyone', and should be case insensitive
var s2='xhello everyone';
console.log(someFunction(s2,matcher);
//Should return nothing (either NULL or FALSE or "" would be fine) since s2 doesn't start with 'Hello'
三个答案的演示:https://jsfiddle.net/dynvgn1k/
答案 0 :(得分:2)
不需要使用正则表达式只需使用:
s1.toLowerCase().indexOf(matcher.toLowerCase()) === 0 && s1.substr(matcher.length)
//=> everyone
matcher='hi'
s1.toLowerCase().indexOf(matcher.toLowerCase()) === 0 && s1.substr(matcher.length)
//=> false
使用toLowerCase
会使其忽略大小写比较。 indexOf
返回主题和位置中搜索字符串的位置0
表示在开始时找到搜索字词。
答案 1 :(得分:2)
一个简单的正则表达式就可以了
function someFunction(str,matcher) {
var regex = new RegExp('^' + matcher, 'i');
return str.replace(regex, '');
}
答案 2 :(得分:0)
你可以这样做
var metadata = {
snippet: {
title: $('#title').val(),
description: $('#description').text(),
tags: this.tags,
categoryId: this.categoryId
},
status: {
privacyStatus: "public"
}
};