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?
Why not just use [az]+
instead of \\w
? (Make sure to add the case-insensetive flag, or use [a-zA-Z]
instead)
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).
采用:
str = str.replace(/[a-z]+/ig, 'x');
Try using [a-zA-Z]
instead. \\w
is equivalent to [a-zA-Z0-9_]
.
str = str.replace(/[a-zA-Z]+/g, 'x');
You can try this regex:
str = str.replace(/[a-z]+/ig, 'x');
[az] - 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 az and capital letters AZ. This is for use without the case modifier.
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.