简体   繁体   English

如果使用JavaScript以其他字符串开头将其剥离

[英]Strip string from other string if it starts with it using JavaScript

Using JavaScript, how do I strip a string from other string if the other string starts with the first string? 使用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'

Demo for the three answers: https://jsfiddle.net/dynvgn1k/ 演示三个答案的示例: https : //jsfiddle.net/dynvgn1k/

No need to use regex just use: 无需使用正则表达式,只需使用:

s1.toLowerCase().indexOf(matcher.toLowerCase()) === 0 && s1.substr(matcher.length)
//=>  everyone

matcher='hi'
s1.toLowerCase().indexOf(matcher.toLowerCase()) === 0 && s1.substr(matcher.length)
//=> false

Use of toLowerCase will make it ignore case comparison. 使用toLowerCase将使其忽略大小写比较。 indexOf returns position of search string in subject and position 0 means search word is found at start. indexOf返回主题中搜索字符串的位置,位置0表示在开始时找到搜索词。

A simple regex will do it 一个简单的正则表达式就可以做到

function someFunction(str,matcher) {
    var regex = new RegExp('^' + matcher, 'i');
    return str.replace(regex, '');
}

You can do like this 你可以这样

var matcher='Hello';
var s1='hello everyone';
s=s1.split(" ");
(s[0].toUpperCase() ===matcher.toUpperCase() )?console.log(s[1]):console.log("nothing");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM