views:

60

answers:

4

I want to change a string which start 'a' and end 'n'.

For example: "action" I want to replace 'ctio' and all starting 'a' and finishing 'n' with ''.

How can do it?

+2  A: 

in Javascript:

var substitute = "\"";
var text = "action";
var text = text.replace(/\b(a)([a-z]+?)(n)\b/gim,"$1" + substitute + "$3");
// result = a"n ... if what  you really want is a double quote here
Robusto
and how can I replace with 'asdasd' instead of ''
sundowatch
@sundowatch: Just change the string assigned to `substitute`.
T.J. Crowder
@Robusto: because of the non-greedy quantifier and the lack of a word boundary, this solution would have a problem with a word beginning with `a`, ending in `n` and having another `n` or `a` anywhere in the middle of the word.
Andy E
@Andy e's head: Good point. I'll revise. Thanks.
Robusto
@sundowatch: T.J. Crowder gave you the answer. I only want to add that a " is what your question looked like it wanted as the replacement string. The replacement can, of course, be any string.
Robusto
thanks I want to use '<' and ' ' instead of 'a' and 'n' I can't do it
sundowatch
@sundowatch: Sure you can. '<' is a valid string for regexp searching. So is '>'. For example, /<\/*[a-z]+[^>]+>/gim will find any tag in a string of HTML markup.
Robusto
+4  A: 
return theString.replace(/\ba[a-z]*n\b/ig, '')
KennyTM
This would replace the entire word, he only needs to replace the letters between `a` and `n`.
Andy E
thanks I want to use '<' and ' ' instead of 'a' and 'n' I can't do it
sundowatch
@sun: You want to strip HTML tags?
KennyTM
+1  A: 
Alec
+1  A: 

try this following

str.replace(/\ba(\w+)n\b/igm,'');

to the question in the comment use th following comment

var sub = "hello";
str.replace(/(<)(\w+)(")/igm,"$1" + sub + "$3");
josnidhin
your code is right. But I want to use '<' and ' ' instead of 'a' and 'n'. What must I do?
sundowatch