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
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?
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>
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.