1

I have specific word (for example "in") after which I want to replace a space with a no-break space. I used plain replace: from " in " to " in" + String.fromCharCode(160).

However words are not always surrounded by spaces - for eample in this sentence:

This is sample text (in which there are parentheses).

So I need a regex to replace a space after "in" with a no-break space. How can I do this?

1 Answer 1

3

You may use a word boundary before in

.replace(/\bin /g, "in" + String.fromCharCode(160))

To make it case insensitive:

.replace(/\b(in) /ig, "$1" + String.fromCharCode(160))

Here is the regex demo

See demo below:

console.log(
    "In this is sample text (in which there are parentheses)."
     .replace(/\b(in) /ig, "$1" + String.fromCharCode(160))
);

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

3 Comments

Thanks, works perfectly. How can use a variable instead of "in"? I tried new RegExp("\b(" + preposition + ") ", "ig"); but it doesn't work.
Using the constructor is the right way, just the backslash must be doubled: new RegExp("\\b(" + preposition + ") ", "ig");
Oh, I see - I have to escape the backslash to make the string literal express "\b" because otherwise the first backslash would escape the "b" and wouldn't be passed to the constructor. is it true?

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.