0

How can I use javascript to find a word in a string which is wrapped in parenthesis, and then style this particular word. I would like users in a CMS to wrap any word they would like in parenthesis, which would then automatically make this word bold. I know I can get them to wrap the words in tags but I would like to make it easier for them.

For example, if I had the string

Hello (World)

How do I target the characters in between the parenthesis and style these characters, so it looks like this.

Hello <b>World</b>
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
sonicfroots
  • 107
  • 1
  • 2
  • `targetElemtn.innterHTML=str.split("(").join("").split(")").join("")` – iAmOren Sep 15 '20 at 18:24
  • `.replace(/\(([^)]+)\)/g, '$1')`. However, this requires html-escaping *before* doing the bolding. – Bergi Sep 15 '20 at 18:39
  • 1
    Does this answer your question? [Get Substring between two characters using javascript](https://stackoverflow.com/questions/14867835/get-substring-between-two-characters-using-javascript) – Heretic Monkey Sep 15 '20 at 18:45

3 Answers3

0

`targetElemtn.innterHTML=str.split("(").join("<tag[+attrs]>").split(")").join("</tag>")

function go() {
  var target=document.getElementById("target");
  var input=document.getElementById("input").value;
  var opener=document.getElementById("opener").value;
  var closer=document.getElementById("closer").value;
  target.innerHTML=input
    .split("(").join(opener)
    .split(")").join(closer)
  ;
}
<h3>Replace parentheses with tag</h3>
Input: <input id="input"><br>
Tag opener: <input id="opener"><br>
Tag closer: <input id="closer"><br>
<button onclick="go()">Go!</button>
<div id="target"></div>

Try <b> + </b>, <span style="color:red"> + </span>...

iAmOren
  • 2,760
  • 2
  • 11
  • 23
0

My suggestion:

form.onsubmit = () => {
  textarea.value = textarea.value.replace(/{(.*?)}/g, '<b>$1</b>');
  return false;
};
<form id="form">
  <textarea style="width:100%" name="textarea" id="textarea">Hello {world}! Hello {world}! Hello {world}!</textarea>
  <button type="submit">Submit</button>
</form>
AbsoluteBeginner
  • 2,160
  • 3
  • 11
  • 21
-1

Check for the whole string for parenthesis and replace those with code which will make inner code bold.

let str = "Hello (world)"; 
str = str.replace("(","<strong>");
str = str.replace(")", "</strong>");

This will only work if updating will also invoke rendering process in browser.

Sanky
  • 11
  • 5