0

I have a string say "abcd/data/efgh". Now I need to replace text between two '/' character in this string with some other data.

for ex: I want "abcd/data/efgh" to be replaced with "abcd/newtext/efgh".

how can I do it with reg exp in javascript?

2
  • Have you already tried something and failed? Commented Apr 21, 2015 at 9:54
  • can you show what you have so far? have you looked at http://www.regexr.com/ Commented Apr 21, 2015 at 9:54

4 Answers 4

1

Using replace, but because javascript doesn't have lookbehinds, you need to replace it with a string concatenated with slashes:

var x = 'abcd/data/efgh';
var s = 'newtext';
console.log(x.replace(/\/[^/]+\//, '/'+s+'/'));// gives: abcd/newtext/efgh
Sign up to request clarification or add additional context in comments.

Comments

0

Have e try with:

'abcd/data/efgh'.replace(/\/[^/]+\//, '/newtest/')

Output:

abcd/newtest/efgh

Comments

0

Try this:

"abcd/data/efgh".replace(/\/(.+)\//, '/newtext/')

or

"abcd/data/efgh".replace(/^(.+\/)(.+)(\/.+)$/, '$1newtext$3')

Comments

0

you should try this code snippet

var x = 'abcd/data/efgh';
var s = 'newtext';
console.log(x.replace(/(/.[^/]+/)/g, '/'+s+'/'));

Hope this would help you. Thanks!!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.