So I have a string of the English alphabet for example. But I don't know the alphabet very well but I do know that it starts with "abc" and that it ends in "xyz". I want to remove letters "b" to "x". I want to do something like str = str.replace("bc*x",""); or str = str.replace("bc"*"x",""); but I don't know how I can make it work or even if whether Asterisk will work like this in JavaScript.

how can I remove something like everything except for "efg" from "abcdefghijklm" without know what anything is except for "ef"?

Dani AI

Generated

You are close. In JavaScript, String.replace only treats * as a wildcard when you pass a RegExp, and even then * repeats the previous token. So "bc*x" means b, then zero-or-more c, then x. To remove everything from the first b through the first x you want .*? (any chars, non-greedy) between them.

const input = 'abcdefghijklmnopqrstuvwxyz';
const result = input.replace(/b.*?x/, '');   // => 'ayz'

If you specifically know the string starts with abc and ends with xyz, you can preserve those ends and drop the middle in one shot by capturing each end and replacing with the captures:

const collapsed = input.replace(/^(abc).*?(xyz)$/, '$1$2');  // => 'abcxyz'

For your follow-up about keeping exactly efg (or removing everything in front of it): was on the right track that . matches one character. You can capture ef plus the next char and replace the whole string with just that capture. This also avoids manual index math that needed with substring.

// Keep only 'ef' + next char (e.g., 'efg'); empty string if 'ef' not found
const onlyThree = input.includes('ef') ? input.replace(/^.*?(ef.).*$/, '$1') : '';

// Remove everything before 'efg' (keep 'efg' and the rest)
const tailFromEfg = input.replace(/^.*?(?=efg)/, '');

Notes:

  • Add the g flag if there may be multiple b...x segments to remove: /b.*?x/g.
  • .* is greedy; use .*? to stop at the first x. If you truly want the last x, drop the ? or anchor to the end.

Recommended Answers

All 5 Replies

how can I remove something like everything except for "efg" from "abcdefghijklm" without know what anything is except for "ef"?

var alpha = 'abcdefghijklm';
var pattern = 'ef';
var re = new RegExp(pattern+".");
result = alpha.replace(re,"");
alert(result);

using for loop?

http://jsfiddle.net/cLLfq/

I don't understand this.

var alpha = 'abcdefghijklm';
var pattern = 'ef';
var re = new RegExp(pattern+".");
result = alpha.replace(re,"");
alert(result);

Is there a way to make result=efg? Or even just remove everything infront of efg.

Is there a way to make result=efg?

   var result  = alpha.match("efg");

Or even just remove everything infront of efg.

   var result = alpha.substring(alpha.match("efg").index);

Many Thanks To All Of You! :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.