简体   繁体   中英

Return string between square brackets and slashes inside

How to return string/values between square brackets and slashes inside like :

var valueX = "[/This is Value/]"

After catch, I need result : This is Value.

Thanks for your help.

Using replace :

'[/This is value/]'.replace(/\[\/(.*?)\/\]/, '$1'); // "This is value"

Use the global flag ( //g ) to replace all occurences :

'[/a/] [/b/] [/c/] [//]'.replace(/\[\/(.*?)\/\]/g, '$1'); // "a b c "

Use a Regular Expression :

var valueX = "[/This is value/]";
valueX.replace(/^\[\/(.*)\/\]$/, '$1');

Breaking it down, ^ matches the start of the line. \\[\\/ matches the initial [/ ; the backslashes are to stop them being interpreted as special characters. (.*) means match zero or more * of any character . and save it as a group () . \\/\\] is the final /] , and $ matches the end of the line. The $1 in the replacement string tells it to use the first matched group, in our case the zero or more of any character.

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