0

Say I had the following string:

var str = '(1 + foo + 3) / bar';

And I want to replace all strings just with the letter 'x'. I tried:

str = str.replace(/\w/g, 'x');

This results in:

(x + xxx + x) / xxx

Instead, I would like the result to be:

(1 + x + 3) / x

How would I do this? How would I find just the words that don't have digits and replace the word to a single letter?

1

5 Answers 5

3

Why not just use [a-z]+ instead of \w? (Make sure to add the case-insensetive flag, or use [a-zA-Z] instead)

Sign up to request clarification or add additional context in comments.

Comments

2
str = str.replace(/\b[a-z]+\b/ig, 'x');

The \b matches a word boundary. That way 'foo2' won't turn into 'x'. As others mentioned \w includes numbers, but ALSO the underscore, so you won't want to use that. The i modifier does case insensitive matching (so that you can read a little easier).

Comments

1

Use:

str = str.replace(/[a-z]+/ig, 'x');

Comments

1

You can try this regex:

str = str.replace(/[a-z]+/ig, 'x');

[a-z] - To indicate that you are looking for any letter.

+ To indicate that you are looking for a combination (xxx).

i To indicate that the text match can be case insensitive.

g - to indicate you are looking for all matches across the string.

or

you can use

   [a-zA-Z]

it will look for small letters a-z and capital letters A-Z. This is for use without the case modifier.

Comments

1

Try using [a-zA-Z] instead. \w is equivalent to [a-zA-Z0-9_].

str = str.replace(/[a-zA-Z]+/g, 'x');

1 Comment

Actually, \w is [a-zA-Z0-9_]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.