Perocat
Perocat

Reputation: 1521

Add 'whatever' to string in Javascript

I have a function in Javascript which replace a textarea with CKEDITOR.

document.getElementById("text").action=CKEDITOR.replace(
         'body_content',
         {toolbar : 'big',
          height : '450',
          enterMode : CKEDITOR.ENTER_BR}
);

Now I'd like to replace 3 textareas with CKEDITOR on the same function. The 3 areas have name body_contentSOMETHING.

How can I write an expression to replace SOMETHING with whatever?

EDIT: whatever is not defined. should be something like *.exe on windows file reseach

Upvotes: 0

Views: 544

Answers (3)

Jonathan Lonowski
Jonathan Lonowski

Reputation: 123513

Assuming body_content{{something}} is an id, you can use an attribute selector to select them and loop:

var content_areas = document.querySelectorAll('textarea[id^="body_content"]');

for (var i = 0, l = content_areas.length; i < l; i++) {
    content_areas[i].action = CKEDITOR.replace(
         content_areas[i],
         {toolbar : 'big',
          height : '450',
          enterMode : CKEDITOR.ENTER_BR}
    );
}

For compatibility with IE 8, you can use textarea[id|="body_content"] (|= vs ^=), but this expects the value to be whole or followed by a -:

<textarea id="body_content-something"></textarea>

Or add a class to the elements to query by:

<textarea id="body_contentsomething" class="body_content"></textarea>
var content_areas = document.querySelectorAll('.body_content');

// ...

Also, without knowing what document.getElementById("text") is supposed to refer to, I'm not sure how to keep that in the snippets.

Upvotes: 2

Ingo B&#252;rk
Ingo B&#252;rk

Reputation: 20043

Based on an answer from this SO thread you can traverse the DOM like this (jsfiddle):

function getElementsByIdStartsWith(selectorTag, prefix) {
    var items = [];
    var elements = document.getElementsByTagName(selectorTag);
    for (var i = 0; i < elements.length; i++) {
        if (elements[i].id.lastIndexOf(prefix, 0) === 0) {
            items.push(elements[i]);
        }
    }

    return items;
}

var affectedElements = getElementsByIdStartsWith("textarea", "body_content");
for(var i = 0; i < affectedElements.length; i++) {
    affectedElements[i].action = CKEDITOR.replace( /* ... */ );
}

However, this is not very efficient and sounds like an XY problem to me. It would be better to avoid this in the first place, for example by tagging the textareas you want to replace with a common class. Then you could simply do

var affectedElements = document.getElementsByClassName("common-class");

Upvotes: 1

Web User
Web User

Reputation: 7736

var updatedString = originalString.replace(/SOMETHING$/g,"whatever");

Upvotes: 0

Related Questions