Jump to content

regexp match


Nati323
 Share

Recommended Posts

hello, i have a problem

suppose in need to sress all a chars , so i do something like this:

txt = "d c a vv x c x";document.write(txt.replace(/[a]/g, "<b> a </b>"));

but, what i need to do if want to stress the chars a , b and c?

txt = " a vv x b  d c c x";document.write(txt.replace(/[abc]/g, ? ));

?

 

Link to comment
Share on other sites

Perhaps something like...

var str = 'a b c d e f g h a';var chars ='abc';var outstr = '';for(var i=0 ; i<str.length ; i++){  if (chars.indexOf(str[i])!=-1){    outstr += '<b>'+str[i]+'</b>';  }else{    outstr += str[i];  }}

Regex can sometimes seem like the obvious solution -- until you benchmark the code and discover it is very slow.

 

You can read about Regex approaches here... https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace

Link to comment
Share on other sites

first of all thank you very much, second:

 

 

Regex can sometimes seem like the obvious solution -- until you benchmark the code and discover it is very slow

you right in case like this one, where the rexexp is simple , so you can solve this with string functions, but if you have a complex exp like a URL exp and you want to bold the all url's in some text, what do you do then?

what i mean that i remember that in some programming languages there is some thing like a variable that contains the match , for example :

txt.replace(/[abc]/g, "<b> %match </b>")

%match contains the match from the regexp, there is something like this in js?

For example in php:

 

$result = preg_replace('/([abc])/', "<b>1</b>" ,$my_text);
Edited by Nati323
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...