Fane
Fane

Reputation: 2074

Find word with certain character in javascript and replace whole word

I want to search for the char $ in a string. However, this char can be joined to multiple things, even whitespaces. Few examples:

" $ "
"$another"
" $an other"
" on$more "

What I want to do is remove the WHOLE word after finding $ so the outcome for the examples would be:

" "
""
"  other"
" "

I hope I made my point... is this possible to do without loops in pure JavaScript?

Upvotes: 0

Views: 602

Answers (2)

Shrinivas Shukla
Shrinivas Shukla

Reputation: 4453

Use regex

/([^ "]*\$[^ "]*)/g

See working regex here.

Check out this fiddle.

var re = /([^ "]*\$[^ "]*)/g; 
var str = '" $ " ; "$another" ; " $an other" ; " on$more ";';
var subst = ''; 
 
var result = str.replace(re, subst);

alert(result);

Upvotes: 4

iplus26
iplus26

Reputation: 2637

You just need to use [\S]*\$[\S]* regular expression and the replace() method.

var strings = [" $ ", "$another", " $an other", " on$more "];

var re = /[\S]*\$[\S]*/;

for (var i = 0; i < strings.length; i++) {
    strings[i] = strings[i].replace(re, '');
}


console.log(strings);

and you will get [ ' ', '', ' other', ' ' ]

Upvotes: 1

Related Questions