admin管理员组文章数量:1397102
Imagine I have the following multi-line Javascript string:
school
apple
~carrot
dog
I want to take any line that starts with "~" and replace it with "#(contents of line)#". So in this example I want to find "~carrot" and replace it with "#carrot#".
I'm trying to e up with a solution using regular expressions but can't figure out a way to replace some matched string with a modified version of itself (with the prepended/appended characters.)
Any help would be appreciated, hoping one example will turn on the lightbulb...
Imagine I have the following multi-line Javascript string:
school
apple
~carrot
dog
I want to take any line that starts with "~" and replace it with "#(contents of line)#". So in this example I want to find "~carrot" and replace it with "#carrot#".
I'm trying to e up with a solution using regular expressions but can't figure out a way to replace some matched string with a modified version of itself (with the prepended/appended characters.)
Any help would be appreciated, hoping one example will turn on the lightbulb...
Share Improve this question edited Aug 21, 2012 at 14:35 ARW asked Aug 21, 2012 at 14:22 ARWARW 3,4167 gold badges34 silver badges43 bronze badges 4- 2 Is "carrot" a constant string that can be hardcoded or the contents of a variable? – Mark Byers Commented Aug 21, 2012 at 14:24
-
And what exactly do you want to mach? Lines starting with
~
? You have to provide some more information. What makes~carrot
so special that you want to replace it? – Felix Kling Commented Aug 21, 2012 at 14:25 - Sorry, yes carrot is a variable and yes I want to replace any lines that start with "~" with "#(contents of line)#". Thanks! – ARW Commented Aug 21, 2012 at 14:33
- Carrot is just an example, I would not know what it actually was in advance. – ARW Commented Aug 21, 2012 at 14:34
2 Answers
Reset to default 9thestring.replace(/~(\w+)/g, "#$1#");
The parentheses "capture" the word (\w+
) and the $1
in the result references what's captured.
It's really easy. Suppose you have your string in OldString
var OldString = "school apple ~carrot dog";
var myNewString = OldString.replace(/~carrot/, "#carrot#");
document.write("Old string = " + OldString);
document.write("<br />New string = " + myNewString);
Hope it helps
本文标签: regexFind substring in Javascript and prependappend some charactersStack Overflow
版权声明:本文标题:regex - Find substring in Javascript and prependappend some characters - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744122547a2591807.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论