Jump to content

regexp match


Nati323

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

You want to insert whitespace into a string? I suppose you would process the string in a loop.

 

Also I would suggest that you learn to not use document.write().

Link to comment
Share on other sites

no whitespace, i want to do something like this, suppose i have a string like this:

 

a b c d e f g h a

i want to change it to this :

 

<b>a</b><b>b</b><b>c</b> d e f g h <b>a</b>

 

2) i know it was just for the example...

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
×
×
  • Create New...