I was wondering if it was possible to replace certain strings but not others that contain the same value in javascript. For example, say I had the text A AB
and wanted to replace only the standalone A
but not the A in AB. (Note: I know that I could do this manually in this case, but I plan on using scenarios like this throughout large blocks of text) Is there an algorithm or built in js command for doing this?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
- Can php detect if javascript is on or not?
You can achieve this using regular expressions in javascript,
will replace the charecters which occurs for the first time.
will replace the all occurances of "A" with "AB"
in addition to others answers, you could also write: string=string.replace(/a(?=\s)/,""); (?= means it will replace 'a' only if the next characers are space/tab, etc.. you could also write different regex instead of \s if you need other condition (only the 'a' will match ,not the condition regex in the (?=...)
for your other question in the comment(in Asaph answer)you can write:
str = str.replace(RegExp("\\b"+x+"\\b",'g'),'');
If you wish to replace just the stand-alone letter "A", then you may want something like:
Then you can do:
Note that this also removes white space arounding the letter.
Edit
To keep whitespace:
Use a regular expression with word boundaries.