简体   繁体   中英

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)

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, '-')

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM