maimok
maimok

Reputation: 373

Javascript - Using .replace to remove the word "and" from string

I have a string that I am attempting to remove the word "and" from. I am attempting this by using the .replace method in javascript. I am able to remove the word "and" but the end result is not what I am expecting.

I would like my string to be returned similar to the console.log(testString) where the entire string is returned as "i-have-a-test-test-test" without any spacing in between. Currently, my attempt with console.log(newString) returns the string without the - in between each word.

My expected outcome is to have a return result as :

I-have-a-test-test-test

const string = "I have a test and test and test" 

const newString = string.replace(/([^a-zA-Z0-9]*|\s*)\s\and/g, '-')

const testString = string.replace(/([^a-zA-Z0-9]*|\s*)\s/g, '-')
console.log(newString)
console.log(testString)

Upvotes: 0

Views: 66

Answers (3)

ikiK
ikiK

Reputation: 6532

const string = "I have a test and test and test"; 
const string2= string.split(" ").join("-").split("and").join("").split("--").join("-");
console.log(string2)

Upvotes: 1

user2263572
user2263572

Reputation: 5606

var s = "I have a test and test and test" 
s = s.replace(/ and /g, '-').replace(/ /g, '-')

or

var s = "I have a test and test and test" 
s = s.replace(/ and | /g, '-')

Upvotes: 3

jprice92
jprice92

Reputation: 415

This will give your expected outcome based on the scenario you provided:

const string = "I have a test and test and test" 
const newString = string.replaceAll('and ', '').replaceAll(' ','-')
console.log(newString)

String.prototype.replaceAll() source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll

Upvotes: 0

Related Questions