2

I have a string for example:

var string = 'This is a test sentence. Switch the characters. i .';

I want to switch position of every occurrence of the letter 'i' with the character following it except if the following character is a 't' or a non character like 'spaces' or 'line breaks'. So the result output should be some thing like:

Thsi si a test sentence. Switch the characters. i . // switches 's' but not 't' and 'space'

Is such a task possible with regular expressions? The characters I am working with are unicode characters. 'i' is just for an example. Which means matching all characters isn't a good idea. May be a not expression? I have tried some looping replaces but these aren't elegant (or efficient). Any ideas?

2 Answers 2

4

You can use a replace with a regex of that form:

var string = 'This is a test sentence. Switch the characters. i .';
var result = string.replace(/(i)(?![t\s])(.)/g, "$2$1");

jsfiddle demo

(i) matches and captures i into the variable $1.

(?![t\s]) prevents the matching of t and space.

(.) matches and captures any other character into the variable $2.

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

3 Comments

Elegant one liner solution. Works great.
This is great. I am sorry but I am weak with regex. How does this change if let's say we want to check the preceding character?
@pewpewlasers You could perhaps use another capture group (JS unfortunately doesn't support lookbehinds). Let's say another condition to what we have is that when i is preceded by a space, no switching should be made. You could do: string.replace(/(\S|^)(i)(?![t\s])(.)/g, "$1$3$2"); The \S will match a non-space, ^ will match the beginning of a line if the string is like var string = 'island';. The regex is going to match either \S or (indicated by |) ^.
1

You can use regex:/(i)([^t\W])/gi

Code :

var string = 'This is a test sentence. Switch the characters. i .';
string.replace(/(i)([^t\W])/gi,"$2$1");

DEMO

Explanation :

enter image description here

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.