3

I have a simple string and trying to convert [~sample] to @sample. For example:

var string = 'Completely engineer client-based strategic [~theme] areas before cross [~media] technology';
string.replace('[~', '@');

I have tried above solution but it only convert the first one and the ] can not be removed.


now I learnt how to use /g

3
  • 4
    You should really try harder. Google is your friend. Questions here are expected to show at least one line of what you tried. How to Ask Commented Mar 16, 2016 at 20:48
  • 2
    [~sample] to @smaple or to @sample? I'm asking just to be sure it was a typo Commented Mar 16, 2016 at 20:53
  • @WashingtonGuedes it's clearly a typo. Commented Mar 16, 2016 at 20:54

6 Answers 6

4

The issue is a bit more complicated than simply nesting .replace [@ and ]

var string = 'Strategic [~theme] areas with cross [~media] technology [this is fine] ok?';

document.body.innerHTML = string.replace(/\[~([^\]]+)\]/g, '@$1');

The ([^\]]+) makes sure to capture any character that is not an ] but is delimited by [~ and ], which is a better solution in any case preventing text like [don't mess with me] to be... messed.

The RegExp is explained in detail here

Sign up to request clarification or add additional context in comments.

3 Comments

"'Strategic [~theme] areas with cross [~media] technology [this is fine] ok?'" is not string at OP ? Why include requirement that is not described at original Question at an Answer ?
@guest271314 to keep better solutions always visible here on StackOverflow.
@RokoCBuljan Yes, though string at solution is not original string at Question, nor included as description of requirement at Question. How did you determine that [ ] not containing ~ should be replaced, or not replaced ? There is no criteria for such an instance at Question ?
3

Try this code:

string.replace(/(\[~)(\w+)(\])/g, function(match, p1, p2, p3) {
  // p1 = [~
  // p2 = theme / media / whateverWord
  // p3 = ]
  return '@' + p2
  // Returns @whateverWord
})

In the 1st group:

  • \[ will select a [
  • ~ will select a ~

In the 2nd group:

  • \w will select any alphanumeric character or an _
  • The + states that the alphanumeric character must appear at least once, i.e. there must be at least 1 letter between the [~ and ]

In the 3rd group:

  • \] will select any ]

In the function:

  • match is not used in the output, but it contains the whole matched substring
  • p1 contains the [~
  • p2 contains the word between the [~ and ], i.e. theme or media
  • p3 contains the ]

The return statement returns an @, followed by the word between the [~ and ]

This will replace all [~ with @


Here is a working example:

var string = 'Completely engineer client-based strategic [~theme] areas before cross [~media] technology. Also, [this tag] [will be kept]'

document.body.innerHTML = string.replace(/(\[~)(\w+)(\])/g, function(match, p1, p2, p3) {
  return '@' + p2
})


Edit: Actually, you can make it simpler:

string.replace(/(\[~)(\w+)(\])/g, '@$2')

Check out the demo below:

var string = 'Completely engineer client-based strategic [~theme] areas before cross [~media] technology. Also, [this tag] [will be kept]'

document.body.innerHTML = string.replace(/(\[~)(\w+)(\])/g, '@$2')

The $2 contains the contents of the second capture group, and the second capture group contains the text between the [~ and ]. So the output is an @, followed by the text.

This is simpler and faster than the version above, and takes up less space

4 Comments

Seeing as I apparently just copied your answer, I must now upvote yours lol
wouldn't that screw up " hello [something not a placheloder] " ?
that doesn't consider other square brackets
Doesn't work on this string '[Completely] [engineer] [] client-based strategic [~theme] areas before cross [~media] technology'
3

You could use RegExp /(\[~)|(\])/g

var string = 'Completely engineer client-based strategic [~theme] areas before cross [~media] technology';

var res = string.replace(/(\[~)|(\])/g, function(match, p1, p2) {
  if (p1) return "@";
  if (p2) return ""
});

document.body.textContent = res;

20 Comments

@JDB String at OP does not contain [citation needed] ; nor indicate what result of that portion of string should be ? Not certain why that requirement would be included at comments ?
@guest271314 - Yes, it's a vague question. It doesn't show any research effort and provides a weak description of what needs to be done. Really shouldn't be answering it, but that's your call.
better as in faster to run, less mis-matching, and shorter: str.replace(/\[~(\w+)\]/g, "@$1")
@AdamBuchananSmith No worries. Believe have cast 0 "downvote" , here
@vicneanschi "try this string to see what I mean ''[Completely] [engineer] [] client-based strategic [~theme] areas before cross [~media] technology' " ? That is not string at original Question . Original Question did not address other portions of string that may contain [ or ] characters; including or not including characters within [ , ], nor what expected result should be. How did you determine that [ ] at [Completely] [engineer] [] string should be replaced, or not replaced ?
|
1

The code below uses Regexp to find all group of sequences that start with [~ and end with ]. It also captures the word in between. $1 in the second parameter of replace function references the found word.

var string = 'Completely engineer client-based strategic [~theme] areas before cross [~media] technology'


document.body.innerHTML = string.replace(/\[~(\w+)\]/g, '@$1');

1 Comment

@dandavis I didn't see your comment while I was testing and posing my answer :)
1
"Completely engineer client-based strategic [~theme] areas before cross [~media] technology [with some] other bits.".replace(/\[~([^\]]+)\]/g,"@$1");

You need to qualify the tilde in the search. I'm surprised at all the crazy down voting. People are trying to be helpful here. If someone has a problem with the post and the answers, it's more helpful to explain WHY you downvote and not just go willy-nilly on the down-votes without explaining yourself.

As others have said, google is a friend. Try searching through www.regular-expressions.info for more help.

1 Comment

@Druzion, you covered most of the details in your answer. The main difference is that this replacement is forcing the search to be like [~value] and taking said value as a replacement after a literal @ sign. - The benefit to doing it this way instead of the way you proposed is so that the brackets are protected when the tilde isn't in play. In this proposal, "[don't change me] but [~change] me" would yield "[don't change me] but @ change me" whereas you solution would produce "[don't change me but @ change me" note that the closing bracket is missing on the test using your proposal.
0

I think this is what you are looking for https://jsfiddle.net/DIRTY_SMITH/7oe5kh9L/33/

string.replace(/\[~/g, '@').replace(/\]/g, '');

var string = 'Completely engineer client-based strategic [~theme] areas before cross [~media] technology';
alert("Starting string:" +string);

var res = string.replace(/\[~/g, '@').replace(/\]/g, '');
alert("Final string: "+res)

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.