[英]how to remove all the string after a word in javascript?
I want to remove all the string after a word in javascript like in my case remove everything after "share something " 我想删除javascript中一个单词后的所有字符串,例如在我的情况下删除“共享内容”后的所有字符串
bla
bla bla
share something ...
bla bla bla
<image tag></img>
bla bla bla
bla bla bla
<image tag></img>
It can be done the following way : 可以通过以下方式完成:
var input='bla\n\nbla\n\nShare something ...\n\nbla bla bla\n<image tag></img>bla\n<image tag></img>';
var output = input.split('Share something')[0]+'Share something';
console.log(output);
You want to tokenize and you can use split for that: 您要标记化,可以为此使用split :
Split a string into an array of substrings: 将字符串拆分为子字符串数组:
var str = "How are you doing today?";
var res = str.split(" ");
And to get the first token: res[0] is equal to "How" 并获得第一个令牌: res [0]等于“ How”
In the above example, the delimiter is a space character. 在上面的示例中,定界符是空格字符。 For your specific case, you could make the delimiter "share something " :
对于您的特定情况,可以使定界符“共享某些内容” :
var str = "bla\n\nbla\n\nshare something ...\n\nbla bla bla\n<image tag></img>bla\n<image tag></img>"
var res = str.split("share something ");
Using slice you can get a piece of the array: 使用slice可以得到一部分数组:
var whatyouwant = res.slice(0,0) + "share something";
Or 要么
var whatyouwant = res[0] + "share something";
Another option using String.prototype.indexOf
and String.prototype.substring
: 使用
String.prototype.indexOf
和String.prototype.substring
另一个选项:
var seekString = "Share something...";
var str = "Lots of text<br>Share something...<br>More text and stuff";
var idx = str.indexOf(seekString);
console.log("The index is:"+idx);
if (idx !== -1) {
var result = str.substring(0, idx + seekString.length);
console.log(result);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.