最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

how to remove all the string after a word in javascript? - Stack Overflow

programmeradmin0浏览0评论

I want to remove all the string after a word in javascript like in my case remove everything after "share something "

bla 
bla bla 

share something ...

bla bla bla 
<image tag></img>
bla bla bla 
bla bla bla 
<image tag></img>

I want to remove all the string after a word in javascript like in my case remove everything after "share something "

bla 
bla bla 

share something ...

bla bla bla 
<image tag></img>
bla bla bla 
bla bla bla 
<image tag></img>
Share Improve this question edited Aug 3, 2014 at 8:23 Mritunjay 25.9k7 gold badges57 silver badges70 bronze badges asked Aug 3, 2014 at 8:21 warzone_fzwarzone_fz 4821 gold badge9 silver badges25 bronze badges 3
  • 2 Start from here – hindmost Commented Aug 3, 2014 at 8:27
  • You better wrap "bla.." value inside a tag like span, div etc. – Nipuna Commented Aug 3, 2014 at 8:29
  • ITS already inside a div – warzone_fz Commented Aug 3, 2014 at 8:32
Add a ment  | 

3 Answers 3

Reset to default 4

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);

Another option using String.prototype.indexOf and 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);
}

You want to tokenize and you can use split for that:

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"

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:

var whatyouwant = res.slice(0,0) + "share something";

Or

var whatyouwant = res[0] + "share something";
发布评论

评论列表(0)

  1. 暂无评论