Nicholas Hazel
Nicholas Hazel

Reputation: 3750

Javascript - Splicing strings from certain character to next character

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?

Preliminary Concept:

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

Upvotes: 0

Views: 2422

Answers (3)

Leberecht Reinhold
Leberecht Reinhold

Reputation: 263

You could also do it with a simple regex string

foo.replace(/#[^ ]*/g, ""))

Upvotes: 1

jj689
jj689

Reputation: 456

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

Upvotes: 0

Sam Thadhani
Sam Thadhani

Reputation: 587

foo.substr(0,foo.indexOf("#")). This can get you the required output i suppose if that's what you are looking for.

Upvotes: 1

Related Questions