You could also do it with a simple regex string
foo.replace(/#[^ ]*/g, ""))
Question
Hopefully a basic question, as I'm a bit lost where to begin.
Pretend we have this string in JS:
var foo = "Yes, today #hello #vcc #toomanyhashtags #test we went to the park and danced"
How would I go about dynamically finding the character "#" and removing everything after until it hits a space (or in the instance of #test, until the string ends)?
ie. So the above string would read:
var foo = "Yes, today we went to the park and danced "
I had the concept to loop through the entire strings' characters and if
the character === "#", delete characters until the current loop's item === " ". Is there a shorter way to do this?
var foo = "Hello, this is my test #test #hello";
var stripHashtags = function(x) {
for (i=0; i < x.length; i++) {
if (x[i] !== "#") {
console.log(x[i]);
}
}
};
stripHashtags(foo);
Solution
You could also do it with a simple regex string
foo.replace(/#[^ ]*/g, ""))
OTHER TIPS
foo.substr(0,foo.indexOf("#")). This can get you the required output i suppose if that's what you are looking for.
You could go about this using the indexOf() method available to strings. This returns the character location of the first occurrence of whatever you're looking for. Then use substring
var i = foo.indexOf('#');
foo = foo.substr(0,i);