find_all
find_all

Reputation: 197

Replace standalone string with regex in Javascript

I am trying to write a function to replace any standalone set of matching characters. For example:

var myarray = ["this is", "this is iss"]
var my2array = []
var regex = '/bis/b'

for (const i of myarray) {
  var x = i.replace(regex, "")
  my2array.push(x)
}

console.log(my2array)

My desired output would be:

["this", "this iss"]

I got this working in Python, but am not able to translate it properly to Javascript. Currently my output is just the array values [0] and [1] (not sure why Javascript is doing that).

Anyway, my question is, how can I achieve the desired output using regex in Javascript?

Upvotes: 1

Views: 227

Answers (3)

blhsing
blhsing

Reputation: 106455

@benvc's answer is close but leaves extra spaces after replacements, and therefore does not match the desired output.

You can instead use an alternation of two patterns, one that deals with scenarios with spaces on both sides of is (in which case you can use a positive lookahead pattern to avoid matching the last space to allow leaving a space between words after replacement), and the other that deals with scenarios with spaces on only one side of is, or none at all:

var myarray = ["this is", "this is iss", "is this", "is"]
var my2array = []
var regex = /\s+is\s*(?=\s)|\s*\bis\b\s*/

for (const i of myarray) {
  var x = i.replace(regex, "")
  my2array.push(x)
}

console.log(my2array)

Upvotes: 1

benvc
benvc

Reputation: 15120

You are misunderstanding the regex syntax (forward slashes indicate the start and end of the expression, backslashes are used with various characters to indicate certain character sets). You could replace your regex with the following since I think you intended your regex to replace instances of "is" with word boundaries on either side:

var regex = /\bis\b/

Upvotes: 3

fredericrous
fredericrous

Reputation: 3028

this is not the solution but a working example:

var myarray = ["this is", "this is iss"];
var my2array = [];
var regex = /is/g;

for (const i in myarray) {
  var x = myarray[i].replace(regex, "")
  my2array.push(x)
}

console.log(my2array)

Upvotes: 0

Related Questions