0

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)
maimok
  • 333
  • 1
  • 3
  • 12
  • 1
    Is something like `string.replace(/\band\b/g, "").split(/ +/).join("-")` what you want? – ggorlen Aug 03 '20 at 19:36
  • Does this answer your question? [How to replace all occurrences of a string?](https://stackoverflow.com/questions/1144783/how-to-replace-all-occurrences-of-a-string) – VLAZ Aug 03 '20 at 19:40
  • Also relevant: [Strip everything but letters and numbers and replace spaces that are in the sentence with hyphens](https://stackoverflow.com/q/47457447) - it can work the same but instead of the alphanumeric regex, you can replace `and` followed by replacing all spaces to dashes. – VLAZ Aug 03 '20 at 19:41

3 Answers3

3
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, '-')
user2263572
  • 5,435
  • 5
  • 35
  • 57
1

const string = "I have a test and test and test"; 
const string2= string.split(" ").join("-").split("and").join("").split("--").join("-");
console.log(string2)
ikiK
  • 6,328
  • 4
  • 20
  • 40
0

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

jprice92
  • 387
  • 4
  • 18