How can I replace only the first occurrence of every match?
Example.
The following string
var toReplace='href="/3" href="/3/a" href="a/3" href="h/3/a/3/b"'
after replace should be like:
'href="*" href="*/a" href="*" href="*/a/3/b"'
I use this regex
toReplace.replace(/(href=")[^"]*(\/3)/,'$1*')
but the result is this:
'href="*" href="*/a" href="*" href="*/b" '
The last href in that case becomes href="*/b" instead of href="*/a/3/b"
Any ideas?
[^"]*
will try to match all possible matches.
Use non-greedy/lazy regex
/(href=")[^"]*?(\/3)/
^
|
var toReplace = 'href="/3" href="/3/a" href="a/3" href="h/3/a/3/b"'; var replacedString = toReplace.replace(/(href=")[^"]*?(\\/3)/gi, '$1*'); document.write(replacedString);
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.