简体   繁体   中英

jquery regex replace word space

I'm wondering if anyone could help me. I need to replace a string with another string in HTML code. Let's say there is a headline

I am foo with x-foo bar.

. The word "foo" should be replaced, if it has any char right before itself other than space. So the first " foo" should not be replaced but the second "-foo" should be replaced. Also it should replace foo and Foo.

My code would be something like this:

 $("h2").html( $("h2").html().replace(/Foo|foo/g, "<span class='replacedFoo'>F</span>oo") ); 

This code replaces all foo's and Foo's. But also " foo". Can anyone help?

  • replace "somethingFoo"
  • don't replace " Foo"

Thank you all very much!

change all foo & Foo with a space before it or at the beginning of a line with Bar

$("h2").html( $("h2").html().replace(/\\Sfoo/gi,"Bar") )

\\S matches all non-whitespace characters

$("h2").html( $("h2").html().replace(/(^|\S)([Ff])oo/g, "$1<span class='replacedFoo'>$2</span>oo") );

(\\S) - match any non-whitespace character and capture it so we can put it back after replacing.

([Ff]) - match both cases of 'F' and capture so we can replace with the same case.

"$1<span... - insert the non-whitespace character we found at the beginning of the match.

...replacedFoo'>$2</span>... - insert the same case of 'F' we found in the match.

 function replaceFoo(str) { return str.replace(/(\\S)([Ff])oo/g, "$1<span class='replacedFoo'>$2</span>oo"); } console.log(replaceFoo('I am fooFoo')); console.log(replaceFoo('Foo foo foo foofoo')); 

To make it more complicated: What we have:

<h2>This is Something-Foo and Dr. Foo</h2>

What we want:

<h2>This is <strong>Something-</strong><span class="replacedFoo">F</span>oo and Dr. Foo</h2>
  • Replace the whole word right before "Foo" with strong-tag.
  • Replace the F of "Foo" if there is no space but any other character right before "Foo" - match "foo" and "Foo".
  • Do not replace " Foo".

Any more regex-masters? :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM